gpt4 book ai didi

c++ - 在 C++ 中将两个对象塞进一个字节中

转载 作者:行者123 更新时间:2023-12-04 00:12:52 26 4
gpt4 key购买 nike

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 字节的位之一可能是用于表示 bool 值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 使用单个字节。我怀疑我想做的事情可能很平常,并且可能有一个更简单、更快或更标准的解决方案来做到这一点。有没有更好的解决方案将两个对象塞进一个字节?

最佳答案

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

#include  <iostream>

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


int main() {
std::cout << sizeof(A);
}

Demo

关于c++ - 在 C++ 中将两个对象塞进一个字节中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67191753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com