C 语言中的位域?
大家好,
有没有办法我们可以在那些不是结构或联合的任何成员的变量上声明指定位字段的变量。如果没有,那么无论如何我们可以通过指定它的位数来声明变量允许使用。
谢谢 麦迪
HI all,
Is there anyway by which we can declare variable specifying bit fields on those which are not any members of structures or unions.If not,then is there anyway by which we can just declare a variable by specifying the number of bits it is permitted to use.
Thanks
maddy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一种非常简单且古老的技术是只定义一些 #define 变量,其值对应于位位置,然后使用 AND 和 OR 运算来根据需要清除或设置它们。
例如,
然后使用它们来设置标准变量中的位位置。 例如,
效率不高或不聪明,但易于阅读。
编辑 - 添加
如果您希望限制哪些位有效,请设置一个掩码值来应用,如下所示:
作为示例
,显然 someVariable 将是 byte、unsigned int 或 unsigned long,但假设您只需要 11 位的无符号数集整数(16 位)。
A really simple and old technique is to just define a number of #define variables whose values correspond to bit locations and then use AND and OR operations to clear or set them as appropriate.
e.g.
You then use them to set bit locations in a standard variable e.g.
Not efficient or clever but easy to read.
edit - added
If you wish to restrict which bits are valid for use then setup a mask value to apply as follows:
As an example
Obviously someVariable is going to be byte, unsigned int or unsigned long, but say that you want only 11 bits set of an unsigned int (16 bits).
否 - 除非它恰好与内置类型大小相同(例如 8、16、32 或 64 位),否则您需要将其嵌入到结构中。
No - unless it happens to be the same size as a built-in type (e.g. 8, 16, 32 or 64 bits) then you would need to embed it in a struct.
不,您应该使用所示的技术 这里
No, you should use the technique shown here
使用除内置类型之外的位来声明变量没有任何好处。因为编译器最终会为其保留8、16、32或64位的空间。例如,如果您声明变量 unsigned x:5;然后编译器将创建8位空间来存储它。因为CPU无法读取不是8倍数的内存
there is no benefit in declaring a variable with bits other than built-in type. because compiler will ultimately reserve space for it 8,16,32 or 64 bits.e.g if you declare variable unsigned x:5; then compiler will create 8 bits of space to store it. because CPU can't read memory which is not multiple of 8
在 ARM 环境中,使用 C 语言配置 SOC 的硬件组件时,按位字段操作的使用很常见。
LPC_SC->FLASHCFG = (LPC_SC->FLASHCFG & ~0x0000F000) | FLASHCFG_Val;
使用 FLASHCFG_Val 的值更新配置寄存器中的 4 位字段。
或者, while (!(LPC_SC->PLL1STAT & (1<<10)));//等待PLOCK1
测试状态寄存器中的单个位,其中 1<<10 表示第 10 位位置。
In the ARM context, use of bitwise field operations are common when configuring the hardware components of the SOC using C.
LPC_SC->FLASHCFG = (LPC_SC->FLASHCFG & ~0x0000F000) | FLASHCFG_Val;
updates a 4 bit field in a configuration register with the value of FLASHCFG_Val.
Or, while (!(LPC_SC->PLL1STAT & (1<<10)));// Wait for PLOCK1
to test a single bit in a status register where 1<<10 indicates the 10th bit position.