将字节数组转换为int

oli*_*dev 10 c#

我试图在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
}
Run Code Online (Sandbox Code Playgroud)

谁能给我一些想法?

Ben*_*igt 25

BitConverter 是正确的方法.

您的问题是因为您在承诺时仅提供了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;
}
Run Code Online (Sandbox Code Playgroud)

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