简体   繁体   中英

c# how to store two 4 bit numbers into one byte

So I have two 4 bits number (between 0 and 15):

int a = 1;
int b = 15;

And I want to store them into 1 byte .

This is what I have try:

byte[] bytesA = BitConverter.GetBytes(a);
byte[] bytesB = BitConverter.GetBytes(b);
byte a = bytesA[0];
byte b = bytesB[1];

Sins a byte is 8 bits and you have 2 4 bit values, you will need to shift one of the values to occupy the high 4 bits of the resulting byte, like so:

byte ab = (byte)((a << 4) | (b & 0xF));

To get a out of ab :

byte a = (byte)((ab >> 4) & 0xF);

To get b out of ab :

byte b = (byte)(ab & 0xF);

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