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
}
类A
使用2个字节。但是,由于c
永远不会获得大于2^7-1的值(如注释中所指定的),因此可以使用c
字节的一位来表示布尔值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;
}
};
现在,类A
使用了一个字节。我怀疑我想要做的事情可能是很常见的,也许有一个更简单、更快或更标准的解决方案来做到这一点。有没有更好的解决方案把两个对象塞进一个字节?
发布于 2021-04-21 16:18:23
您可以使用位域为成员提供特定的位大小。
#include <iostream>
struct A {
unsigned char c : 7;
bool b : 1;
};
int main() {
std::cout << sizeof(A);
}
发布于 2021-04-21 20:58:47
如果您的代码绝对必须将这两个值存储在单个8位字段中,请使用掩码:
struct a {
unsigned char value;
unsigned char get_c() const { return value & 0x7F; }
void set_c(unsigned char c1} {
value &= 0x80;
value |= (c1 & 0x7F);
}
bool get_b() const { return value & 0x80; }
void set_b(bool b1) { value &= 0x7F; value |= (b1 ? 0x80 : 0); }
};
显然,使用位域更简单,但是位域布局的细节取决于实现;您不能保证将两个加起来为8位的字段存储在单个8位对象中。
https://stackoverflow.com/questions/67191753
复制相似问题