TerribleDog
TerribleDog

Reputation: 1247

Merge 2 integers into 1 byte

I have been working in this since yesterday and I can't seem to fully understand the bit shifting. What I'm trying to accomplish is that, I need to merge 2 numbers into 1 byte. The first number in the 1st four bits, and the second in the last four bits.

0001 = 1

0110 = 6

And then make them 1 byte from the binary "00010110".

After that, I also want to extract the 1 and the 6 separately. How do I do that?

All I can do is the extraction that I got from another question here:

int b = Convert.ToByte(value); 
byte[] b1 = new byte[2];
b1[0] = b >> 4;
b1[1] = b & 0x0F;

Upvotes: 0

Views: 414

Answers (1)

zx485
zx485

Reputation: 29022

Assuming that value1 is 0001 = 1 and value2 is 0110 = 6, you can merge both values with an OR operation |.

byte result = 0;
try {
  byte b1 = Convert.ToByte(value1); 
  byte b2 = Convert.ToByte(value2); 
  result = (b1 << 4) | (b2 & 0x0F);
} catch (OverflowException) {
  ... // Handle 'Int too big' situation.
}

Upvotes: 1

Related Questions