如何使用位操作在单个整数中编码和解码两个数字
How can i encode and decode two number in a single integer using bit manipulations?
我正在学习位操作,然后我想到了这个。假设我有两个数字,第一个在 [1,6] 范围内,第二个在 [0,3] 范围内。现在,第一个数字最多可以存储 3 位,第二个数字最多可以存储 2 位。如何使用一个 int32 将它们都存储在其中。谢谢。
编码:
// a : range of [1,6], bit0 ~ bit2
// b : range of [0,3], bit3 ~ bit4
// c : encoded int32
c = 0;
c |= (a | b << 3);
解码:
a = (c & 0x00000007);
b = (c & 0x00000018) >> 3;
int32_t composite = first_number << 2 | second_number;
会这样做。
然后second_number
占用两个最低有效位,您可以使用 composite & 3
提取它。
first_number
占据了"左边"的三个位,你可以用composite >> 2
提取它。
如果您只需要将两个数字打包到一个 int 中,而不是位操作,您可能希望使用位字段。这样,您可以将两个字段存储在一个 int-field 的空间中,并按名称访问它们。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何使用位操作在单个整数中编码和解码两个数字
- C++用于解码MKV视频(杜比数字/ AVC)的库
- 我将ASCII字转换成数字,但我一直试图解码它们.如何转换1=a, 2=b, 28=ab等?(psudeocode好)
- 数字 > 2^31-1 的变体编码/解码问题
- 对rapidjson,编码只是一个数字字符串,然后解码它