c - 将 int 设置为特定位

标签 c bit-manipulation bit

这可能有点奇怪,但这是我遇到的问题。

我有一个这样的结构:

typedef struct smallStruct{
    unsigned int First10 : 10;
    unsigned int Next10 : 10;
    unsigned int Third10 : 10;
    unsigned int extra : 1;
} small

我需要能够传入一个 int 并将其设置为适合 First10 的 10 位,然后是 Next10 的另一个 int,等等。出现这种情况的原因是因为我需要能够在一个 4 字节的变量中存储 4 条不同的信息,这是我能想到的最有效的方法。

我需要为此进行位移吗?

最佳答案

你可以简单地赋值;位域逻辑负责必要的修改:

small make_small(int a, int b, int c) {
  small result = { a, b, c, 0 };
  return result;
}

void update_first(int value, small * s) {
  s->First10 = value;
}

// etc.

关于c - 将 int 设置为特定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959776/

相关文章:

c - 按位运算实现逻辑右移

c - 了解 C 中的位级浮点乘法?

c# - 解释 MySQL 数据库整数值

c - 二进制文件和文本文件在存储方面的区别?

c - 从 C 中的 uint16_t 获取最低字节

C 编程 - 来自 rand() 的奇怪输出

c - 如何初始化一个只有 -1 值的数组

c - 这个计划如何评价?

c - 如何访问结构内部的 union ?

c - Gtk3 窗口背景图像