Store 2 4-bit numbers in 1 8 bit number

2019-08-24 04:04发布

I am new in thinking about binary numbers. I'm wondering if there is a way to encode 2 4-bit numbers (i.e. hex-encoded numbers) into 1 8-bit number. So if I had a and 5 as the hex numbers, that would be 10 and 5. Maybe there is a way to store that in 1 8 bit number, in such a way that you can get it out of the 8-bit number back into its component 4-bit parts.

[10, 5]! = 15
15! = [10, 5]

Wondering if there is such a way to encode the numbers to accomplish this.

It seems like it is possible, because the first value could be stored in the first 16 digits, then the next value could be stored in the remaining, using 16 as 1, 32 as 2, 48 as 3, etc.

Can't tell if the answer here is how to do it:

How can i store 2 numbers in a 1 byte char?

Not really giving what I'd want:

> a = 10
10
> b = 5
5
> c = a + b
15
> d = (c & 0xF0) >> 4
0
> e = c & 0x0F
15

Maybe I'm not using it right, not sure. This seems like it could be it too but I am not quite sure how to accomplish this in JavaScript.

How to combine 2 4-bit unsigned numbers into 1 8-bit number in C

Any help would be greatly appreciated. Thank you!

2条回答
再贱就再见
2楼-- · 2019-08-24 04:20

I think the first post has the key.

Having a and 5 as the two 4-bit hex numbers to store, you can store them in a variable like:

var store = 0xa5;

or dynamically

var store = parseInt('0x' + ('a' + '9'), 16);

Then to extract the parts:

var number1 = ((store & 0xF0) >> 4).toString(16)
var number2 = ((store & 0x0F)).toString(16)

I hope this helps.

查看更多
smile是对你的礼貌
3楼-- · 2019-08-24 04:31

Yes this is supported in most programming languages. You have to do bitwise manipulation. The following is an example in Java.

To encode (validate input beforehand)

byte in1 = <valid input>, in2 = <valid input>;
byte out = in1<<4 | in2;

To decode:

byte in = <valid input>;
byte out1 = in>>4;
byte out2 = in & 0x0f;
查看更多
登录 后发表回答