Combine 2 numbers in a byte

流过昼夜 提交于 2021-02-08 15:52:36

问题


I have two numbers (going from 0-9) and I want to combine them into 1 byte. Number 1 would take bit 0-3 and Number 2 has bit 4-7.

Example : I have number 3 and 4.
3 = 0011 and 4 is 0100.
Result should be 0011 0100.

How can I make a byte with these binary values?

This is what I currently have :

    public Byte CombinePinDigit(int DigitA, int DigitB)
    {
        BitArray Digit1 = new BitArray(Convert.ToByte(DigitA));
        BitArray Digit2 = new BitArray(Convert.ToByte(DigitB));

        BitArray Combined = new BitArray(8);
        Combined[0] = Digit1[0];
        Combined[1] = Digit1[1];
        Combined[2] = Digit1[2];
        Combined[3] = Digit1[3];  

        Combined[4] = Digit2[0];
        Combined[5] = Digit2[1];
        Combined[6] = Digit2[2];
        Combined[7] = Digit2[3];
    }

With this code I have ArgumentOutOfBoundsExceptions


回答1:


Forget all that bitarray stuff.

Just do this:

byte result = (byte)(number1 | (number2 << 4));

And to get them back:

int number1 = result & 0xF;
int number2 = (result >> 4) & 0xF;

This works by using the << and >> bit-shift operators.

When creating the byte, we are shifting number2 left by 4 bits (which fills the lowest 4 bits of the results with 0) and then we use | to or those bits with the unshifted bits of number1.

When restoring the original numbers, we reverse the process. We shift the byte right by 4 bits which puts the original number2 back into its original position and then we use & 0xF to mask off any other bits.

This bits for number1 will already be in the right position (since we never shifted them) so we just need to mask off the other bits, again with & 0xF.

You should verify that the numbers are in the range 0..9 before doing that, or (if you don't care if they're out of range) you can constrain them to 0..15 by anding with 0xF:

byte result = (byte)((number1 & 0xF) | ((number2 & 0xF) << 4));



回答2:


this should basically work:

byte Pack(int a, int b)
{
    return (byte)(a << 4 | b & 0xF);
}

void Unpack(byte val, out int a, out int b)
{
    a = val >> 4;
    b = val & 0xF;
}


来源:https://stackoverflow.com/questions/16214497/combine-2-numbers-in-a-byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!