如何将2个数字存储在1个字节的字符中? [英] How can i store 2 numbers in a 1 byte char?

查看:430
本文介绍了如何将2个数字存储在1个字节的字符中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有标题的问题,但是如果没有,我怎么能只用4位来表示整数呢?

I have the question of the title, but If not, how could I get away with using only 4 bits to represent an integer?

编辑,实际上我的问题是如何.我知道在像c这样的语言中有1个字节的数据结构,但是如何使用char这样的东西来存储两个整数?

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?

推荐答案

您可以在一个字节中存储两个4位数字(称为b,它是一个无符号字符).

You can store two 4-bit numbers in one byte (call it b which is an unsigned char).

使用十六进制很容易看到:在b=0xAE中,两个数字是A和E.

Using hex is easy to see that: in b=0xAE the two numbers are A and E.

使用口罩将其隔离:

a = (b & 0xF0) >> 4

e = b & 0x0F

您可以轻松定义用于在字节的适当部分设置/获取两个数字的函数.

You can easily define functions to set/get both numbers in the proper portion of the byte.

注意:如果4位数字需要带有符号,则打包和开箱时必须正确扩展符号,这会使事情变得更加复杂.

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.

这篇关于如何将2个数字存储在1个字节的字符中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆