gpt4 book ai didi

c++ - 使用类修改字节中的位

转载 作者:搜寻专家 更新时间:2023-10-31 02:24:14 31 4
gpt4 key购买 nike

我想直接修改一个字节中的一个位。

在 GCC 中,您可以按如下方式进行:

struct virtualByte {
unsigned char b0 : 1;
unsigned char b1 : 1;
unsigned char b2 : 1;
unsigned char b3 : 1;
unsigned char b4 : 1;
unsigned char b5 : 1;
unsigned char b6 : 1;
unsigned char b7 : 1;
} __attribute__((__packed__));

#define sbit(_byte, _pos) (((volatile struct virtualByte *)&_byte)->b ## _pos)

用法:

unsigned char myByte = 0x00;

#define firstBit sbit(myByte, 0)

firstBit = 1; // Implicit myByte |= 0x01;

为了让事情变得更整洁,我想要一个为我做这件事的类(class)。我想出了以下概念:

unsigned char myByteRef = 0x00;

Byte myByte(&myByteRef);

myByte[0] = 1; // Implicit myByteRef |= 0x01;

fprintf(stderr, "%2.2X\n", myByteRef);

但这行不通,因为在 C++ 中,您不能返回对单个位的引用。重载构造函数也不起作用。

是否有可能实现此类行为?赋值运算符应直接修改其底层字节(而不是一组字节)。

最佳答案

您想使用 std::bitset :

std::bitset<12> someBits; // 12 bits
someBits[0] = true; // set 1st bit
std::cout << someBits.count() << '\n'; // prints 1

std::bitset<12>::reference bit5 = someBits[5];
bit5 = true;
std::cout << someBits.count() << '\n'; // prints 2

您可以使用 index operator以您想要的方式返回对位的引用。请注意,此引用不是 bool&,而是 std::bitset::reference:

关于c++ - 使用类修改字节中的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28266140/

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