简体   繁体   中英

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;

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM