如何将byte解释为int?

问题描述 投票:3回答:2

我有一个从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,can't implicitly convert string to int是什么意思?...它让我困惑。

c# .net-3.5 compact-framework bytebuffer uint8t
2个回答
6
投票

你快到了。假设你想从前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的回答。


4
投票

如果我理解你,你有byte(不是string)阵列

  byte[] arr = new byte[] {
    182, 243, 157, 63,  // Real32 - C# Single or float (e.g. 1.234f)
    123                 // uInt8  - C# byte            (e.g. 123) 
  };

要获得floatbyte,你可以试试BitConverter

  // read float / single starting from 0th byte
  float realPart = BitConverter.ToSingle(arr, 0);
  byte bytePart = arr[4];

  Console.Write($"Real Part: {realPart}; Integer Part: {bytePart}");

结果:

  Real Part: 1.234; Integer Part: 123

同样的想法(BitConverter类)如果我们想编码arr

  float realPart = 1.234f;
  byte bytePart = 123;

  byte[] arr = 
     BitConverter.GetBytes(realPart)
    .Concat(new byte[] { bytePart })
    .ToArray();

  Console.Write(string.Join(" ", arr));

结果:

  182 243 157 63 123
© www.soinside.com 2019 - 2024. All rights reserved.