C++中直接比较两个8位(1字节)的值

Directly compare Two 8 Bit (1 Byte) values in C++

我想知道,有没有一种方法可以像比较 int 一样比较 8 个 bit/1 字节值?

例如:

// Start with these as false
bool int_comp = false;
bool byte_comp = false;

// Set the ints
int a_int = 128;
int b_int = 128;

// Set the bytes
char a_byte = 0xC0; // 11000000
char b_byte = 0xC0; // 11000000

// This comparison works
if (a_int == b_int)
   int_comp = true;

// This comparison does not work, however
if (a_byte == b_byte)
   byte_comp = true;

在这种情况下,字节比较不起作用。有没有办法以类似于我们比较整数的方式来比较字节?


编辑:事实证明这确实有效 - 感谢您的回复。我在我的代码中做了一些额外的事情,但我没有在此处捕获导致问题的原因。本质上,我使用的是 static_cast 并认为它可以工作,但没有。

这是我正在做的事情:

// Start with these as false
bool int_comp = false;
bool byte_comp = false;

// Set the ints
int a_int = 128;
int b_int = 128;

// Set the bytes
int8_t a_byte = 0xC0; // 11000000
char b_byte = 0xC0; // 11000000

// This comparison works
if (a_int == b_int)
   int_comp = true;

// This comparison does not work, however
//
// Turns out that using static_cast here did not do what I thought it would do,
// even though printing out the bits using std::bitset showed that the bits
// of the casted value were the same.
//
if (a_byte == static_cast<int8_t>(b_byte))
   byte_comp = true;

I'm wondering, is there a way to compare 8 bit values similarly to the way that we could compare an int?

是的,有。示例:

std::uint8_t a_octet = 0xC0; // 11000000
std::uint8_t b_octet = 0xC0; // 11000000
if (a_octet == b_octet)

... is there a way to compare 1 byte values ...

是的,有。示例:

unsigned char a_byte = 0xC0; // 11000000
unsigned char b_byte = 0xC0; // 11000000
if (a_byte == b_byte)

char a_byte = 0xC0; // 11000000

在字节大小为 8 位且 char 是有符号类型的系统上,这并不像您期望的那样工作,因为在这种情况下 0xC0 超出了可表示值。最大可表示值将是 0x7f。

否则您的示例有效。