简体   繁体   English

将uint8_t与C ++中的十六进制进行比较

[英]Compare uint8_t with hexadecimal in C++

Let's say I have uint8_t bytes[maxBytes]; 假设我有uint8_t bytes[maxBytes]; .

Now I want to compare the lower 6 bits of the first byte ( bytes[0] ) with 0x3c . 现在我想比较第一个字节( bytes[0] )的低6位和0x3c

I tried to do it like this: 我试着这样做:

bytes[0] & 0x3f == 0x3c

Unfortunately, this did not produce the expected result. 不幸的是,这并没有产生预期的结果。 (ie it's always false, even though when I print out bytes[0] & 0x3f , it is 0x3c ) (即它总是假的,即使我打印出bytes[0] & 0x3f ,它是0x3c

I've played around with this some more and found out that 我已经玩了一些这个,并发现了

bytes[0] & 0x00 == 0x00

is sometimes true, and sometimes false. 有时是真的,有时是假的。 (Same with bytes[0] & 0x0 == 0x0 and bytes[0] & 0x00 == 0x0 ). (与bytes[0] & 0x0 == 0x0以及bytes[0] & 0x00 == 0x0 )相同。 Shouldn't it always be true? 它不应该永远是真的吗?

What is going on here? 这里发生了什么? How can I make my 0x3c comparison work? 如何使我的0x3c比较工作?

Sitenote: I'm running this code on an arduino w/ atmega328pb MCU. Sitenote:我在arduino w / atmega328pb MCU上运行此代码。

You need parentheses: 你需要括号:

(bytes[0] & 0x3f) == 0x3c

This is because of the weird precedences of & and | 这是因为&|的奇怪优先级 which were inherited from C, which inherited them from B (Dennis Ritchie described this precedence problem in https://www.bell-labs.com/usr/dmr/www/chist.html ). 它们是从C继承而来的,它继承自B(Dennis Ritchie在https://www.bell-labs.com/usr/dmr/www/chist.html中描述了这个优先级问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM