Converting Int32 to a 24-bit signed integer

I need to convert an Int32 value to a 3-byte (24-bit) integer. Endianness remains the same (a little), but I cannot figure out how to move the sign correctly. The values ​​are already tied to the correct 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 the 32-bit version.

+3
source share
2 answers

If you want to do this conversion, just delete the top byte of the four-byte number. The two-component representation will take care of the sign correctly. If you want to store a 24-bit number in a variable Int32, you can use v & 0xFFFFFFto get only the lower 24 bits. I saw your comment about a byte array: if you have space in the array, write all four bytes of the number and just send the first three; which is typical for small systems.

+1
source

Found: 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 an array.

EDIT:

as Jeremiah pointed out, you 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
}
+2
source

Source: https://habr.com/ru/post/1790383/


All Articles