600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > C语言进制的格式字符 GB汉字文件转换成C语言Unicode十六进制字符串格式

C语言进制的格式字符 GB汉字文件转换成C语言Unicode十六进制字符串格式

时间:2018-12-20 10:00:07

相关推荐

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";

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。