C中移位运算符的具体用法是什么
我认为移位运算符会移位应用它的整数或字符的内存,但以下代码的输出让我感到惊讶。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
uint64_t number = 33550336;
unsigned char *p = (unsigned char *)&number;
size_t i;
for (i=0; i < sizeof number; ++i)
printf("%02x ", p[i]);
printf("\n");
//shift operation
number = number<<4;
p = (unsigned char *)&number;
for (i=0; i < sizeof number; ++i)
printf("%02x ", p[i]);
printf("\n");
return 0;
}
它运行的系统是小端并产生以下输出:
00 f0 ff 01 00 00 00 00
00 00 ff 1f 00 00 00 00
有人可以提供一些关于轮班运算符的详细工作的参考吗?
I thought shift operator shifts the memory of the integer or the char on which it is applied but the output of the following code came a surprise to me.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
uint64_t number = 33550336;
unsigned char *p = (unsigned char *)&number;
size_t i;
for (i=0; i < sizeof number; ++i)
printf("%02x ", p[i]);
printf("\n");
//shift operation
number = number<<4;
p = (unsigned char *)&number;
for (i=0; i < sizeof number; ++i)
printf("%02x ", p[i]);
printf("\n");
return 0;
}
The system on which it ran is little endian and produced the following output:
00 f0 ff 01 00 00 00 00
00 00 ff 1f 00 00 00 00
Can somebody provide some reference to the detailed working of the shift operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我想你已经回答了你自己的问题。机器是小端,这意味着字节存储在内存中,最低有效字节位于左侧。所以你的记忆代表:
如你所见,第二个值与第一个值相同,左移 4 位。
I think you've answered your own question. The machine is little endian, which means the bytes are stored in memory with the least significant byte to the left. So your memory represents:
As you can see, the second is the same as the first value, shifted left by 4 bits.
一切正确:
(1 * (256^3)) + (0xff * (256^2)) + (0xf0 * 256) = 33 550 336
(0x1f * (256^3)) + (0xff * (256^2) )) = 536 805 376
33 550 336 * (2^4) = 536 805 376
左移 4 位与乘以 2^4 相同。
Everything is right:
(1 * (256^3)) + (0xff * (256^2)) + (0xf0 * 256) = 33 550 336
(0x1f * (256^3)) + (0xff * (256^2)) = 536 805 376
33 550 336 * (2^4) = 536 805 376
Shifting left by 4 bits is the same as multiplying by 2^4.
我认为 printf 让你感到困惑。以下是这些值:
您现在能读取输出吗?
I think you printf confuses you. Here are the values:
Can you read you output now?
它不会移动内存,而是移动位。所以你得到了这个数字:
将这个数字向左移动 4 位(一个十六进制数字)后,你得到:
这正是转换为小尾数法时得到的输出。
It doesn't shift the memory, but the bits. So you have the number:
After shifting this number 4 bits (one hexadecimal digit) to the left you have:
Which is exactly the output you get, when transformed to little endian.
您的循环按照字节存储在内存中的顺序打印字节,并且在大端机器上输出会有所不同。如果您想以十六进制打印该值,只需使用 %016llx。然后您将看到您所期望的结果:
第二个值左移 4。
Your loop is printing bytes in the order they are stored in memory, and the output would be different on a big-endian machine. If you want to print the value in hex just use %016llx. Then you'll see what you expect:
The second value is left-shifted by 4.