c# – 如何将byte解释为int?

我有一个从Cpp程序中获取的字节数组.

arr[0..3] // a real32,
arr[4]    // a uint8,

我如何将arr [4]解释为int?

(uint)arr[4] // Err: can't implicitly convert string to int.
BitConverter.ToUint16(arr[4]) // Err: Invalid argument.
buff[0+4] as int // Err: must be reference or nullable type

我是否必须将连续的零字节解释为UInt16?

好的,这是混乱.最初,我定义了我的课程.

byte[] buff;
buff = getSerialBuffer();

public class Reading{
    public string scale_id;
    public string measure;
    public int measure_revised;
    public float wt;
}
rd = new Reading();
// !! here is the confusion... !!
// Err: Can't implicitly convert 'string' to 'int'
rd.measure = string.Format("{0}", buff[0 + 4]); 
// then I thought, maybe I should convert buff[4] to int first ? 
// I throw all forms of conversion here, non worked.
// but, later it turns out:
rd.measure_revised = buff[0+4]; // just ok.

所以基本上,我不明白为什么会这样

rd.measure = string.Format("{0}", buff[0 + 4]); 
//Err: Can't implicitly convert 'string' to 'int'

如果buff [4]是一个字节而字节是uint8,它是什么意思不能隐式地将字符串转换为int?…它让我困惑.

解决方法:

你快到了.假设你想从前4个字节中获得一个32位的int(很难解释你的问题):

BitConverter.ToInt32(arr, 0);

这表示从arr获取4个字节,从索引0开始,并将它们转换为32位int. (docs)

请注意,BitConverter使用计算机的字节序,因此在x86 / x64上这将是little-endian.

如果要使用显式字节序,则需要手动构造int:

int littleEndian = arr[0] | (arr[1] << 8) | (arr[2] << 16) | (arr[3] << 24);
int bigEndian = arr[3] | (arr[2] << 8) | (arr[1] << 16) | (arr[0] << 24);

如果你需要前4个字节的32位浮点数,请参阅Dmitry Bychenko的回答.

上一篇:java基于NIO的分散读取文件,然后统一聚合后写入文件


下一篇:Java – ByteBuffer.remaining()问题