繁体   English   中英

将字节数组转换为 int

[英]Convert byte array to int

我正在尝试在 C# 中进行一些转换,但我不知道该怎么做:

private int byteArray2Int(byte[] bytes)
{
    // bytes = new byte[] {0x01, 0x03, 0x04};

    // how to convert this byte array to an int?

    return BitConverter.ToInt32(bytes, 0); // is this correct? 
    // because if I have a bytes = new byte [] {0x32} => I got an exception
}

private string byteArray2String(byte[] bytes)
{
   return System.Text.ASCIIEncoding.ASCII.GetString(bytes);

   // but then I got a problem that if a byte is 0x00, it show 0x20
}

谁能给我一些想法?

BitConverter是正确的方法。

您的问题是因为您在承诺 32 时只提供了 8 位。请尝试在数组中使用有效的 32 位数字,例如new byte[] { 0x32, 0, 0, 0 }

如果要转换任意长度的数组,可以自己实现:

ulong ConvertLittleEndian(byte[] array)
{
    int pos = 0;
    ulong result = 0;
    foreach (byte by in array) {
        result |= ((ulong)by) << pos;
        pos += 8;
    }
    return result;
}

目前尚不清楚您的问题的第二部分(涉及字符串)应该产生什么,但我想您想要十六进制数字? 前面的问题所述, BitConverter也可以提供帮助。

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first), 
// reverse the byte array. 
if (BitConverter.IsLittleEndian)
  Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
  1. 这是正确的,但是您缺少Convert.ToInt32 '想要' 32 位(32/8 = 4字节)的信息来进行转换,因此您不能只转换一个字节:`new byte [] {0x32}

  2. 绝对和你一样的麻烦。 并且不要忘记您使用的编码:从编码到编码,您有“每个符号的不同字节数”

一种快速简单的方法是使用 Buffer.BlockCopy 将字节复制到 integer:

UInt32[] pos = new UInt32[1];
byte[] stack = ...
Buffer.BlockCopy(stack, 0, pos, 0, 4);

这具有额外的好处,即能够仅通过操作偏移量将大量整数解析为数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM