在 C++ 中的单个字节中填充两个对象

Rem*_*i.b 3 c++ memory

class A
{
   char c; // c represents a value varying from 0 to 2^7-1 (I don't need a bigger range)
   bool b; // b is a boolean value
}
Run Code Online (Sandbox Code Playgroud)

A使用 2 个字节。但是,由于c永远不会获得大于 2^7-1 的值(如注释中所指定),c因此可以使用of 字节的位之一来表示布尔值b。就像是

class A
{
    unsigned char x;   // x represents both a value varying from 0 to 2^7-1 and a boolean value

public:
    A(unsigned char c, bool b)
    {
        assert(c <= 127);
        x = c;
        if (b) x += 128;
    }

    unsigned char getC()
    {
        if (x >= 128) return x - 128; else return x;
    }

    bool getB()
    {
        return x >= 128;
    }
};
Run Code Online (Sandbox Code Playgroud)

现在类A使用单个字节。我怀疑我想做的事情可能很平常,并且可能有一个更简单、更快或更标准的解决方案来做到这一点。有没有更好的解决方案将两个对象塞进一个字节中?

sup*_*per 5

您可以使用位域为成员提供特定的位大小。

#include  <iostream>

struct A {
    unsigned char c : 7;
    bool b : 1;
};


int main() {
    std::cout << sizeof(A);
}
Run Code Online (Sandbox Code Playgroud)

演示

  • 位域是特定于实现的,并且当底层类型不同时,某些编译器“尊重”底层对象(因此“更好”有“unsigned char b : 1;”)。 (3认同)