读《深入理解计算机系统》
第二章 信息的表示与处理
字节序:
大多数intel兼容机采用小端字节序:低字节存放在存储器的低地址,注意是以字节为单位。
12345(十进制) |
低地址--------->高地址
|
0x00003039 |
39 30 00 00 00
|
网络协议采用大端字节序:高字节存放在存储器的低地址。
移位:
据说c语言并没有明确定义有符号数何时用算术移位,何时用逻辑移位。但无符号数必须是逻辑移位。
引用这位朋友的评论,这个描述比较精确
|
“据说”可不好 如果是模棱两可的东西 可以去标准里确认一下
这部分内容C99和C11是一样的
4. The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1× 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1× 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
5. The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1divided by the quantity, 2 raised to the power E2.If E1 has a signed type and a negative value, the resulting value is implementation-defined.
大致意思是说左移的时候,如果操作数是有符号负数,其行为没有定义,其他情况则在低位补零。这一点书中并没有指出要区分负数情况,而是按照无符号数的方式讲解,不过编译器的行为大多是按照这种方式操作负数的。右移操作,对负数的描述是依赖于编译器实现,其他情况使用逻辑移位。
此外,左移位的时候,如果移动的位数大于数据类型占用的位,书中说标准规避了如何做的描述,不过看上面的引用是有明确说明的。假设数据占用w位,移动k位,k>=w,对于这种情况许多机器移动k mod w位。例如:
int i=0xf1 << 32; //32 mod 32,移动0位
i=i<<33; //33 mod 32,移动1位
以上代码在vc下会报告警“行为未定义”,但执行结果确实是移动了k mod w位。
这部分内容C99和C11是一样的
4. The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1× 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1× 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
5. The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1divided by the quantity, 2 raised to the power E2.If E1 has a signed type and a negative value, the resulting value is implementation-defined.