gpt4 book ai didi

c - C 中的位字段?

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:35 25 4
gpt4 key购买 nike

大家好,

有没有我们可以通过它来声明变量指定那些不是结构或 union 的任何成员的位字段。如果没有,那么无论如何我们可以通过指定它是的位数来声明一个变量允许使用。

谢谢麦迪

最佳答案

一个非常简单和古老的技术是只定义一些#define 变量,其值对应于位位置,然后使用 AND 和 OR 操作来适本地清除或设置它们。例如

#define BIT_0 0x0001
#define BIT_1 0x0002
#define BIT_2 0x0004
#define BIT_3 0x0008
#define BIT_4 0x0010

然后您可以使用它们来设置标准变量中的位位置,例如

int someVariable = 0;

someVariable = someVariable | BIT_1; //set bit 1 to 1. someVariable = 2

someVariable = someVariable & ~BIT_1; // clear bit 1. someVariable = 0

效率不高或不聪明,但易于阅读。

编辑 - 添加如果你想限制哪些位是有效的,那么设置一个掩码值来应用,如下所示:

#define VALID_BIT_MASK 0x0009 // thus only bits 3 and 0 are valid

举个例子

someVariable = someVariable | BIT_0 | BIT_2 | BIT_4; // someVariable now has value 21

someVariable = someVariable & VALID_BIT_MASK; // remove invalid bits, someVariable value is now 1

显然 someVariable 将是 byte、unsigned int 或 unsigned long,但假设您只需要 unsigned int 的 11 位集(16 位)。

#define VALID_BIT_MASK 0x07FF; // 011111111111 in binary.

someVariable = someVariable & VALID_BIT_MASK; //strips off unwanted bits.

关于c - C 中的位字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2712142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com