在对结构体进行位移操作时,需要将其成员转换为基本数据类型。
例如,假设我们有以下结构体:
struct Color {
uint8_t red;
uint8_t green;
uint8_t blue;
};
若想将其向左位移 1 位,可以使用如下代码:
Color color = { 255, 255, 255 };
uint32_t packedColor = (color.red << 16) | (color.green << 8) | color.blue;
packedColor <<= 1;
需要注意的是,我们将每个成员先向左位移相应的位数(红色位移 16 位,绿色位移 8 位,蓝色不位移),然后将它们按顺序拼接成一个 32 位的整数。最后,我们将整个 32 位的数据向左位移 1 位。
如果直接对结构体进行位移操作,会出现错误:
Color color = { 255, 255, 255 };
color <<= 1; // ERROR: Invalid operands to binary expression