相关疑难解决方法(0)

为什么bit endianness是bitfields中的一个问题?

任何使用位域的可移植代码似乎都区分了小端和大端平台.有关此类代码的示例,请参阅linux内核中struct iphdr声明.我无法理解为什么位字节序是一个问题.

据我所知,bitfields纯粹是编译器构造,用于促进位级操作.

例如,考虑以下位域:

struct ParsedInt {
    unsigned int f1:1;
    unsigned int f2:3;
    unsigned int f3:4;
};
uint8_t i;
struct ParsedInt *d = &i;
只是一种简洁易懂的说法d->f2.

但是,无论架构如何,位操作都是明确定义的并且可以正常工作.那么,bitfields怎么不便携?

c portability cross-platform low-level bit-fields

54
推荐指数
4
解决办法
3万
查看次数

如何用8个bool值创建一个字节(反之亦然)?

我有8个bool变量,我想将它们"合并"成一个字节.

有一个简单/首选的方法来做到这一点?

相反,如何将一个字节解码为8个独立的布尔值?

我认为这不是一个不合理的问题,但由于我无法通过谷歌找到相关文档,它可能是另一个"非你所有直觉都是错误的"案例.

c++ boolean bit-manipulation bit-packing

20
推荐指数
4
解决办法
2万
查看次数

C 中位域的内存布局 - 无法理解输出

我有这个代码 - http://ideone.com/sXhWxf

#include <stdio.h>

int main(void) {

struct bitfield{
    unsigned a:5;
    unsigned c:5;
    unsigned b:6;
} bit = {1,3,3};

char *p = (char*)&bit;
printf("%d\n",*p);
p++;
printf("%d\n",*p);
// I assumed that the bits are laid out in the below order in the memory.
// Spaces are just for clarity
// 00001 00011 000011
// Also, I asumed that the 'char' will take 8 bits. But I can't understand output.
// According to me the output should be - 8 195 …
Run Code Online (Sandbox Code Playgroud)

c c++ memory bit-fields output

2
推荐指数
1
解决办法
1128
查看次数

从低到高的位顺序/在C中使用位域映射结构

我最近玩C中的位字段,显然,这些位从低到高排序,尽管谷歌不支持这一论点(例如维基百科).

请参考以下代码(http://ideone.com/UwWfJM):

#include <stdio.h>

struct bits {
    unsigned char a : 1;
    unsigned char b : 1;
    unsigned char c : 1;
    unsigned char d : 1;
    unsigned char e : 1;
    unsigned char f : 1;
    unsigned char g : 1;
    unsigned char h : 1;
};

int main(int argc, char **argv)
{
    unsigned char c = 33;
    struct bits *b = (struct bits *) &c;

    printf("dec: %u\n", c);
    printf("bits: %x", b->a);
    printf("%x", b->b);
    printf("%x", …
Run Code Online (Sandbox Code Playgroud)

c struct bit-manipulation bit-fields

1
推荐指数
1
解决办法
168
查看次数