[英]Cramming two objects in a single byte in C++
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
}
Class A
uses 2 bytes. Class
A
使用 2 个字节。 However, as c
is never meant to get a value greater than 2^7-1 (as specified in comments), one of the bit of the byte of c
could be used to represent the boolean value b
.但是,由于
c
永远不会获得大于 2^7-1 的值(如注释中指定),因此c
字节中的一位可用于表示b
Something like就像是
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;
}
};
Now class A
uses a single byte.现在 class
A
使用单个字节。 I suspect what I want to do might be quite usual and there might be a simpler, faster or more standard solution to do just that.我怀疑我想做的事情可能很平常,并且可能有一个更简单、更快或更标准的解决方案来做到这一点。 Is there a better solution to cram two objects into a single byte?
有没有更好的解决方案将两个对象塞进一个字节?
If your code absolutely must store these two values in a single 8-bit field, use masks:如果您的代码绝对必须将这两个值存储在一个 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); }
};
Obviously, using a bit-field is simpler, but the details of how bit-fields are laid out depend on the implementation;显然,使用位域更简单,但位域如何布局的细节取决于实现; you have no guarantee that two fields that add up to 8 bits will be stored in a single 8-bit object.
您无法保证两个加起来为 8 位的字段将存储在单个 8 位 object 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.