简体   繁体   English

如何在1个字节的字符中存储2个数字?

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

I have the question of the title, but If not, how could I get away with using only 4 bits to represent an integer? 我有标题的问题,但是如果没有,我该如何仅使用4位来表示整数呢?

EDIT really my question is how. 编辑真的我的问题是如何。 I am aware that there are 1 byte data structures in a language like c, but how could I use something like a char to store two integers? 我知道在像c这样的语言中有1个字节的数据结构,但是如何使用像char这样的东西来存储两个整数呢?

In C or C++ you can use a struct to allocate the required number of bits to a variable as given below: 在C或C ++中,您可以使用struct将所需的位数分配给变量,如下所示:

#include <stdio.h>
struct packed {
    unsigned char a:4, b:4;
};
int main() {
    struct packed p;
    p.a = 10;
    p.b = 20;
    printf("p.a %d p.b %d size %ld\n", p.a, p.b, sizeof(struct packed));
    return 0;
}

The output is pa 10 pb 4 size 1 , showing that p takes only 1 byte to store, and that numbers with more than 4 bits (larger than 15) get truncated, so 20 (0x14) becomes 4. This is simpler to use than the manual bitshifting and masking used in the other answer, but it is probably not any faster. 输出为pa 10 pb 4 size 1 ,表明p仅占用1个字节,并且大于4位(大于15)的数字被截断,因此20(0x14)变为4。这比使用起来更简单另一个答案中使用的手动移位和屏蔽,但这可能不会更快。

You can store two 4-bit numbers in one byte (call it b which is an unsigned char). 您可以在一个字节中存储两个4位数字(将其称为b ,这是一个无符号字符)。

Using hex is easy to see that: in b=0xAE the two numbers are A and E. 使用十六进制很容易看出:在b=0xAE ,两个数字是A和E。

Use a mask to isolate them: 使用口罩隔离它们:

a = (b & 0xF0) >> 4

and

e = b & 0x0F

You can easily define functions to set/get both numbers in the proper portion of the byte. 您可以轻松定义函数以在字节的适当部分设置/获取两个数字。

Note: if the 4-bit numbers need to have a sign, things can become a tad more complicated since the sign must be extended correctly when packing/unpacking. 注意:如果4位数字需要带符号,则打包和开箱时必须正确扩展符号,这会使事情变得更加复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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