【发布时间】:2019-08-08 14:56:12
【问题描述】:
我有一个从 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是什么意思?...让我很困惑。
【问题讨论】:
-
(uint)arr[4] // Err: can't implicitly convert string to int.这似乎很奇怪...arr的类型是什么? -
您似乎对是否需要 32 位 int 或 16 位 int 感到困惑。
int和uint(Int32和UInt32)是 4 个字节(32 位)。short和ushort(Int16和UInt16)是 2 个字节(16 位)。 -
对不起,它的 arr 是一个字节数组。我想要一个 C# 中不存在的 uin8 ...所以我只想将 arr[4] 用作 int 。
-
uint8存在并且被调用byte。您可以毫无问题地将byte转换为int/uint。所以(uint)arr[4] // Err: can't implicitly convert string to int.会起作用。 -
如果
arr是byte[],那么第一次转换(uint)arr[4]就可以了。 (工作在某种意义上它不会导致给定的错误消息)
标签: c# .net-3.5 compact-framework bytebuffer uint8t