【问题标题】:How to convert utf8 string to utf8 byte array?如何将 utf8 字符串转换为 utf8 字节数组?
【发布时间】:2012-07-17 09:15:26
【问题描述】:

如何将字符串转换为 utf8 字节数组,我有这个示例代码:

这工作正常:

StreamWriter file = new StreamWriter(file1, false, Encoding.UTF8);
file.WriteLine(utf8string);
file.Close();

这是错误的,文件是 ASCII:

byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(utf8string);
FileStream fs = new FileStream(file2, FileMode.CreateNew);
fs.Write(bytes, 0, bytes.Length);
fs.Close();

我想得到这个函数返回的字节数组:

System.IO.File.ReadAllBytes(path_to_file)

因为这可以正常工作:

byte[] datab = File.ReadAllBytes(file1);
FileStream fs2 = new FileStream(file3, FileMode.CreateNew);
fs2.Write(datab, 0, datab.Length);
fs2.Close();

【问题讨论】:

  • 为什么你认为你的第二个例子不起作用?
  • 刚刚问了非常相似的问题:stackoverflow.com/questions/11539559/…
  • 这不能回答你的问题byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(utf8string);

标签: c# .net encoding utf-8


【解决方案1】:

可以再次使用其他选项:

string value = "\u00C4 \uD802\u0033 \u00AE";    
byte[] bytes= System.Text.Encoding.UTF8.GetBytes(value);

更多信息可以关注Encoding.UTF8 Property

【讨论】:

  • 生成的字节数组是否包含尾随 NULL 字符?
  • 仅当输入数组有一个时。这是一对一的副本。
猜你喜欢
  • 2013-09-14
  • 2011-01-18
  • 2017-05-18
  • 2013-09-12
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 2018-05-01
相关资源
最近更新 更多