开发者

Converting Int32 to 24-bit signed integer

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 alr开发者_如何学Ceady 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.


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 use v & 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.


Found this: http://bytes.com/topic/c-sharp/answers/238589-int-byte

int myInt = 800;
byte[] myByteArray = System.BitConverter.GetBytes(myInt);

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

int myInt = 800;
byte[] myByteArray = System.BitConverter.GetBytes(myInt);

if (BitConverter.IsLittleEndian) {
    // get the first 3 elements
} else {
    // get the last 3 elements
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜