从 int 中取出 4 位并转换为 byte
Take 4 bits out of an int and convert to byte
我正在实现一个串行协议。
我需要带 class 个成员并将他们打包成一个 byte[]
消息。
协议字节 #7 是这样的:
位 0-3 - SomeNumricData
位 0-4 - 其他数值数据
我正在尝试从 class 成员构建字节 #7 :
commandData[7] = Convert.ToByte(
Convert.ToByte(SomeNumricData) |
Convert.ToByte(OtherNumericData) << 4
);
我得到:
System.OverflowException: 'Value was either too large or too small for
an unsigned byte
因为没有 4 位数据类型...我怎样才能从整数中取出 4 位,才不会溢出 Convert.ToByte()
?
您提供的号码已溢出。您可以使用下面的代码,但它只需要四个最低有效位。如果数字大于0x0F,其他位将被忽略。
commandData[7] = Convert.ToByte((SomeNumricData & 0x0F) | ((OtherNumericData << 4) & 0xF0));
我正在实现一个串行协议。
我需要带 class 个成员并将他们打包成一个 byte[]
消息。
协议字节 #7 是这样的:
位 0-3 - SomeNumricData
位 0-4 - 其他数值数据
我正在尝试从 class 成员构建字节 #7 :
commandData[7] = Convert.ToByte(
Convert.ToByte(SomeNumricData) |
Convert.ToByte(OtherNumericData) << 4
);
我得到:
System.OverflowException: 'Value was either too large or too small for an unsigned byte
因为没有 4 位数据类型...我怎样才能从整数中取出 4 位,才不会溢出 Convert.ToByte()
?
您提供的号码已溢出。您可以使用下面的代码,但它只需要四个最低有效位。如果数字大于0x0F,其他位将被忽略。
commandData[7] = Convert.ToByte((SomeNumricData & 0x0F) | ((OtherNumericData << 4) & 0xF0));