如何使用位操作在单个整数中编码和解码两个数字

How can i encode and decode two number in a single integer using bit manipulations?

本文关键字:解码 数字 两个 编码 位操作 何使用 单个 整数      更新时间:2023-10-16

我正在学习位操作,然后我想到了这个。假设我有两个数字,第一个在 [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 的空间中,并按名称访问它们。