Store 2 4-bit numbers in 1 8 bit number

青春壹個敷衍的年華 提交于 2019-12-25 03:12:32

问题


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!


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/51219155/store-2-4-bit-numbers-in-1-8-bit-number

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