Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 16-bit signed int to 2-bytes?

Tags:

c#

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.

like image 667
Tristan Demanuele Avatar asked Mar 29 '10 13:03

Tristan Demanuele


People also ask

What is a 2 byte integer?

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.

Why int is 2 bytes?

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.

What is the maximum value of an unsigned int 2 byte in C language *?

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 .

Can you cast int to byte?

An int value can be converted into bytes by using the method int. to_bytes().


1 Answers

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);
like image 62
Jon Skeet Avatar answered Oct 12 '22 07:10

Jon Skeet