I got an array which contains signed int data, i need to convert each value in the array to 2 bytes. I am using C# and i tried using BitConverter.GetBytes(int)
but it returns a 4 byte array.
the 2-byte signed Integer – An automation integer data type that can be either positive or negative. The most significant bit is the sign bit, which is 1 for negative values and 0 for positive values. The storage size of the integer is 2 bytes. A 2-byte signed integer can have a range from -32,768 to 32,767.
An int is guaranteed to have a minimum range from -32768 to 32767, i.e, from -(2^16) to (2^16)–1 which means it must occupy a minimum of 16 bits or 2 bytes.
A short int which has two bytes of memory, has a minimum value range of -32,768 and a maximum value range of 32,767 . An unsigned short int , unsigned meaning having no negative sign (-), has a minimum range of 0 and a maximum range of 65,535 .
An int value can be converted into bytes by using the method int. to_bytes().
A signed 16-bit value is best represented as a short
rather than int
- so use BitConverter.GetBytes(short)
.
However, as an alternative:
byte lowByte = (byte) (value & 0xff);
byte highByte = (byte) ((value >> 8) & 0xff);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With