在阅读K&R书时,我偶然发现了2.9章,该章描述了C语言中的按位运算符。一开始就有这样的主张:
按位与运算符&通常用于掩盖某些位集合,例如 n = n&0177; 将n的所有低位7位设置为零。
我对其真正含义有些困惑。十六进制(如果我理解正确的话)0177如何表示低阶7位?我尝试在代码中对其进行测试,以下是我的工作:
#include <stdio.h>
int main()
{
int n = 1490;
n = n & 0177;
printf("%i\n", n);
}
代码的输出为82。将1490转换为二进制,我得到10111010010,将除7个低阶位之外的所有位都设置为零后,我得到1010010,它实际上等于十进制的82。为了理解逻辑,我手动应用了&(AND)运算符,但得出的数字却完全不同。我做错了什么?
First, notice that 0177 is an octal input, analogous of binary
1111111
= 127 in decimal.But when you do n&something, there are applied the default argument promotions and 127 is converted to the type of
n
, which means, it is converted to something like0000000 0000000 0000000 01111111
-- supposing thesizeof(typeof(n)) = 4
.因此,n&0177将转换为仅在n为1的最低7位上保留1的数字。
还要注意bigendian或littleendian的情况。