将 Int32 转换为 24 位有符号整数
我需要将 Int32 值转换为 3 字节(24 位)整数。字节序保持不变(很小),但我不知道如何适当地移动符号。这些值已经被限制在正确的范围内,我只是不知道如何将 4 个字节转换为 3 个字节。使用 C# 4.0。这是为了硬件集成,所以我必须有24位值,不能使用32位。
I have a need to convert an Int32 value to a 3-byte (24-bit) integer. Endianness remains the same (little), but I cannot figure out how to move the sign appropriately. The values are already constrained to the proper range, I just can't figure out how to convert 4 bytes to 3. Using C# 4.0. This is for hardware integration, so I have to have 24-bit values, cannot use 32 bit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果要进行该转换,只需删除四字节数字的顶部字节即可。二进制补码表示将正确处理符号。如果您想将 24 位数字保留在
Int32
变量中,可以使用v & 0xFFFFFF
仅获取低 24 位。我看到你对字节数组的评论:如果数组中有空间,则写入数字的所有四个字节,然后仅发送前三个字节;不过,这是小端系统特有的。If you want to do that conversion, just remove the top byte of the four-byte number. Two's complement representation will take care of the sign correctly. If you want to keep the 24-bit number in an
Int32
variable, you can usev & 0xFFFFFF
to get just the lower 24 bits. I saw your comment about the byte array: if you have space in the array, write all four bytes of the number and just send the first three; that is specific to little-endian systems, though.找到这个:http://bytes.com/topic/c-sharp/ answers/238589-int-byte
听起来您只需要获取数组的最后 3 个元素。
编辑:
正如耶利米指出的,你需要做类似的事情
Found this: http://bytes.com/topic/c-sharp/answers/238589-int-byte
sounds like you just need to get the last 3 elements of the array.
EDIT:
as Jeremiah pointed out, you'd need to do something like