我正在考虑(因此我正在寻找一种方法来学习这一点,而不是更好的解决方案)是否有可能在结构中获得一组位。
让我通过一个例子来演示。想象一下这样的代码:
#include <stdio.h>
struct A
{
unsigned int bit0:1;
unsigned int bit1:1;
unsigned int bit2:1;
unsigned int bit3:1;
};
int main()
{
struct A a = {1, 0, 1, 1};
printf("%u\n", a.bit0);
printf("%u\n", a.bit1);
printf("%u\n", a.bit2);
printf("%u\n", a.bit3);
return 0;
}
在这段代码中,我们将 4 个单独的位打包在一个结构中。它们可以单独访问,将位操作的工作留给编译器。我想知道这样的事情是否可能:
#include <stdio.h>
typedef unsigned int bit:1;
struct B
{
bit bits[4];
};
int main()
{
struct B b = {{1, 0, 1, 1}};
for (i = 0; i < 4; ++i)
printf("%u\n", b.bits[i]);
return 0;
}
我尝试将 struct B
中的 bits
声明为 unsigned int bits[4]:1
或 unsigned int bits:1[ 4]
或类似的东西无济于事。我最好的猜测是 typedef unsigned int bit:1;
并使用 bit
作为类型,但仍然不起作用。
我的问题是,这样的事情可能吗?如果是,如何?如果不是,为什么不呢? 1 位 unsigned int 是一个有效的类型,那么为什么不能得到它的数组呢?
再说一次,我不想替换它,我只是想知道这样的事情怎么可能。
附:尽管代码是用 C 编写的,但我将其标记为 C++,因为我假设该方法在两种语言中都存在。如果有 C++ 特定的方法(通过使用语言结构,而不是库),我也很想知道。
更新:我完全知道我可以自己进行位操作。过去我已经做过一千次了。我对使用数组/vector 代替并进行位操作的答案不感兴趣。我只是在考虑这个结构是否可行,而不是替代方案。
更新:为不耐烦的人解答(感谢 neagoegab):
代替
typedef unsigned int bit:1;
我可以使用
typedef struct
{
unsigned int value:1;
} bit;
正确使用#pragma pack
最佳答案
NOT POSSIBLE - 这样的构造不可能(here) - NOT POSSIBLE
可以尝试这样做,但结果将是一个位存储在一个字节中
#include <cstdint>
#include <iostream>
using namespace std;
#pragma pack(push, 1)
struct Bit
{
//one bit is stored in one BYTE
uint8_t a_:1;
};
#pragma pack(pop, 1)
typedef Bit bit;
struct B
{
bit bits[4];
};
int main()
{
struct B b = {{0, 0, 1, 1}};
for (int i = 0; i < 4; ++i)
cout << b.bits[i] <<endl;
cout<< sizeof(Bit) << endl;
cout<< sizeof(B) << endl;
return 0;
}
输出:
0 //bit[0] value
0 //bit[1] value
1 //bit[2] value
1 //bit[3] value
1 //sizeof(Bit), **one bit is stored in one byte!!!**
4 //sizeof(B), ** 4 bytes, each bit is stored in one BYTE**
为了从一个字节访问单个位,这里是一个示例(请注意,位域的布局取决于实现)
#include <iostream>
#include <cstdint>
using namespace std;
#pragma pack(push, 1)
struct Byte
{
Byte(uint8_t value):
_value(value)
{
}
union
{
uint8_t _value;
struct {
uint8_t _bit0:1;
uint8_t _bit1:1;
uint8_t _bit2:1;
uint8_t _bit3:1;
uint8_t _bit4:1;
uint8_t _bit5:1;
uint8_t _bit6:1;
uint8_t _bit7:1;
};
};
};
#pragma pack(pop, 1)
int main()
{
Byte myByte(8);
cout << "Bit 0: " << (int)myByte._bit0 <<endl;
cout << "Bit 1: " << (int)myByte._bit1 <<endl;
cout << "Bit 2: " << (int)myByte._bit2 <<endl;
cout << "Bit 3: " << (int)myByte._bit3 <<endl;
cout << "Bit 4: " << (int)myByte._bit4 <<endl;
cout << "Bit 5: " << (int)myByte._bit5 <<endl;
cout << "Bit 6: " << (int)myByte._bit6 <<endl;
cout << "Bit 7: " << (int)myByte._bit7 <<endl;
if(myByte._bit3)
{
cout << "Bit 3 is on" << endl;
}
}
关于c++ - 如何获取结构中的位数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8143220/