Question

I'm looking for a good and efficient way to store integers in bytes.

The situation is the following: I have two integers, Value 1 is "1857" (11bit) and Value 2 is "14" (4bit) and 2 bytes (16bit). What I'm looking for, is to store the 2 integers in the 2 bytes. This mean cut the first integer, put 8 bits in the first byte and the rest plus the second integer in the second byte. Also I need to get them back together.

Is there a way or .net class to do that? I've found the BitConverter class, but thats not what I'm looking for because this class only convert one integer to an full byte array.

Was it helpful?

Solution

You could use bit operators for that: bitwise and (&), or (|), and shift left (<<) and right (>>):

int value1 = 1857;
int value2 = 14;

int result = value1 | (value2 << 11);

To get the original values back you have to reverse that:

int result1 = result & 0x7ff; // 1857
int result2 = result >> 11; // 14
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top