【问题标题】:Get char array from byte array and then back to byte array从字节数组中获取字符数组,然后返回字节数组
【发布时间】:2014-03-01 18:54:13
【问题描述】:

我不知道为什么,但是当你做下一件事时,你将永远不会得到与原始字节数组相同的结果:

var b = new byte[] {252, 2, 56, 8, 9};
var g = System.Text.Encoding.ASCII.GetChars(b);
var f = System.Text.Encoding.ASCII.GetBytes(g);

如果您运行此代码,您会看到 b != f,为什么?! 有什么方法可以将字节转换为字符,然后再转换回字节并与原始字节数组相同?

【问题讨论】:

  • 因为252 不能用作 ASCII 字符(它是 7 位)。所以任意字节数组和字符串之间的转换都是有损的。
  • 你想用这些字符做什么?
  • @L.B 我该如何解决?
  • @AndrewMorton 这有关系吗?
  • @ZilbermanRafael 使用 Convert.ToBase64StringConvert.FromBase64String

标签: c# bytearray


【解决方案1】:

字节值可以是0到255

当字节值> 127,则结果为

System.Text.Encoding.ASCII.GetChars()

总是 '?' ,其值为 63

因此,

System.Text.Encoding.ASCII.GetBytes()

结果总是得到 63(错误值)那些具有初始字节值 > 127


如果你需要TABLE ASCII -II,那么你可以这样做

        var b = new byte[] { 252, 2, 56, 8, 9 };
        //another encoding
        var e = Encoding.GetEncoding("437");
        //252 inside the mentioned table is ⁿ and now you have it
        var g = e.GetString(b);
        //now you can get the byte value 252
        var f = e.GetBytes(g);

您可以阅读类似的帖子

How to convert the byte 255 to a signed char in C#

How can I convert extended ascii to a System.String?

【讨论】:

    【解决方案2】:

    为什么不使用字符?

    var b = new byte[] {252, 2, 56, 8, 9};
    var g = new char[b.Length];
    var f = new byte[g.Length]; // can also be b.Length, doens't really matter
    for (int i = 0; i < b.Length; i++)
    {
       g[i] = Convert.ToChar(b[i]);
    }
    for (int i = 0; i < f.Length; i++)
    {
       f[i] = Convert.ToByte(g[i]);
    }
    

    【讨论】:

      【解决方案3】:

      唯一的区别是第一个字节:252。因为 ascii char 是 1 字节的有符号字符,它的值范围是 -128 到 127。实际上你的输入是不正确的。带符号的字符不能是 252。

      【讨论】:

      • 我不是在谈论实际的 ascii。我在谈论代码中的ascii。我特意这样写,以便于理解。我知道没有什么叫做 ascii unsigned char。
      • 在 c 中,参考答案@Adrian McCarthy,stackoverflow.com/questions/13161199/ascii-table-negative-value 没有“负 ASCII”值这样的东西。 ASCII 为 0 到 127 的值定义字符和控制代码。因此,您的答案在 signed char 上有问题
      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多