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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值