如何将字节解释为int?

时间:2019-03-18 09:19:09

标签: c# .net-3.5 compact-framework bytebuffer uint8t

我有一个来自Cpp程序的 byte数组

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是什么意思?...这使我感到困惑。

2 个答案:

答案 0 :(得分:6)

您快到了。假设您想从前4个字节开始使用32位int(很难解释您的问题):

ggplot(data = sales_data, aes(x = month, y = dept_name)) +
  geom_tile(data = expand.grid(sales_data$month, sales_data$dept_name), 
            aes(x = Var1, y = Var2), fill = NA, col = 'gray50', lty = 2) +
  geom_point(aes(size = revenue, col = revenue), 
             shape = 16, position = position_jitter(seed = 0), show.legend = F) +
  geom_text(aes(label = revenue), vjust = 1.6, position = position_jitter(seed = 0)) +
  theme_bw() +
  theme(
    axis.title = element_blank(),
    axis.ticks = element_blank(),
    plot.background = element_blank(), 
    axis.line = element_blank(), 
    panel.border = element_blank(), 
    panel.grid = element_blank()
    )

这表示从BitConverter.ToInt32(arr, 0); 开始,从arr提取4个字节,然后将它们转换为32位int。 (docs

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

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

BitConverter

如果相反,您希望从前4个字节开始使用32位浮点数,请参见Dmitry Bychenko的回答。

答案 1 :(得分: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