C语言进制的格式字符,GB汉字文件转换成C语言Unicode十六进制字符串格式
可以用在編程環境只能用GB,但程序中的漢字字符串需要用C語言的Unicode十六進制字符串格式表示。可以先在字符串中直接輸入漢字,再用此程序轉換。
源代碼用C#
//ascii & GB to unicode hexadecimal string for C language
//chinese GB code : "啊" --> "\x96\x3F"
private void buttonSaveTextfile_Click(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(PathAndFileName))
{
MessageBox.Show("請設置文件!");
return;
}
try
{
FileStream fs = File.OpenRead(xlsPath.Text);//打開現有文件以進行讀取
FileStream FStream = File./*OpenWrite*/Create(PathAndFileName);
for(long i = 0 ; i < fs.Length ; ++i)
{
byte[] a = new byte[10];
a[0] = (byte)fs.ReadByte();
if(a[0] <= 0x7f)
{
FStream.WriteByte(a[0]);
FStream.WriteByte(0);
}
else
{
a[1] = (byte)fs.ReadByte();
byte[] b = new byte[20];
b = Encoding.Convert(Encoding.Default , Encoding.Unicode, a);
//FStream.WriteByte(b[0]); //也可以輸出Unicode 源 但需要添加文件頭BOM
//FStream.WriteByte(b[1]);
//將Unicode轉換成C語言16進制字符串格式,也可以添加大小端控制
String r = "\\x" + b[1].ToString(@"X2") + "\\x" + b[0].ToString(@"X2"); //+ "\"\""
//尾部一般是需要添加兩個",防止16進制過度解析后面的字符(0-9 a-f A-F)
byte[] c = Encoding.Unicode.GetBytes(r);
for(int j = 0; j < c.Length; ++j) {
FStream.WriteByte(c[j]);
}
++i;
}
}
MessageBox.Show("寫入文件成功!");
fs.Close();
FStream.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
......
private void btn_Select_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "cpp,c文件|*.cpp;*.c|All Files|*.*";//設置打開文件篩選器
openFileDialog.Title = "選擇文件";//設置打開對話框標題
openFileDialog.Multiselect = false;//設置打開對話框中只能單選
openFileDialog.InitialDirectory = Application.StartupPath;
openFileDialog.FilterIndex = 2;
openFileDialog.FileName = "UIInputMethodChn.cpp";
if(openFileDialog.ShowDialog() == DialogResult.OK) //判斷是否選擇了文件
{
xlsPath.Text = openFileDialog.FileName;//在文本框中顯示Excel文件名
try
{
System.IO.File.Move(xlsPath.Text, xlsPath.Text);//移動文件
}
catch(System.Exception ex)//如果移動文件產生異常則說明文件被打開
{
MessageBox.Show(ex.Message, "提示:有點小問題", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
else
{
return;
}
toolStripStatusLabel1.Text = xlsPath.Text;
PathAndFileName = xlsPath.Text.Substring(0, xlsPath.Text.LastIndexOf(".cpp")) + "_.txt";
}
總結
以上是生活随笔為你收集整理的C语言进制的格式字符,GB汉字文件转换成C语言Unicode十六进制字符串格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux c socket编程详解,L
- 下一篇: (数据科学学习手札27)sklearn数