简体   繁体   English

如何在C中获取无符号8位类型的最高有效位

[英]How to get the most significant bit of an unsigned 8-bit type in C

I'm trying to get the most significant bit of an unsigned 8-bit type in C. 我正在尝试获取C中无符号8位类型的最高有效位。

This is what I'm trying to do right now: 这就是我现在正在尝试做的事情:

uint8_t *var = ...;
...
(*var >> 6) & 1

Is this right? 这是正确的吗? If it's not, what would be? 如果不是,那会是什么?

要从uint8_t指针指向的存储器中获取最高有效位,您需要移位7位。

(*var >> 7) & 1

The most standard/correct way of masking bits is to use a readable bit mask of the form 1u << bit . 屏蔽位的最标准/正确方法是使用形式为1u << bit的可读位掩码。 Any C programmer spotting 1u << n in code will know that it is a bit mask - so it is self-documenting code. 任何在代码中发现1u << n C程序员都将知道它是位掩码-因此它是自记录代码。

So if you want bit number 7, you would write 因此,如果您想要数字7,则可以这样写

*var & (1u << 7)

The u suffix is important for rugged code, since you want to avoid accidental implicit promotions to signed types. u后缀对于坚固的代码很重要,因为您要避免意外地将隐式提升为带符号的类型。

另一种选择是简单地应用位掩码并检查结果值:

*var & 0x80u // 1000 0000

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

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