所有8位按位移位会发生什么 [英] What happens with bitwise shift for all 8 bits

查看:125
本文介绍了所有8位按位移位会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c中有一个小查询, 我正在使用数字69的按位左移,它是二进制文件01000101

I have a small query in c, I am using the bitwise left shift on number 69 which is 01000101 in binary

01000101  << 8 

我得到的答案是100010100000000

不是全部都是8个零,即00000000,因为我们将所有8位都向左移,然后用零填充.

Shouldn't it be all 8 zeros i.e. 00000000 as we shift all the 8 bits to left and then pad with zeros.

推荐答案

这是因为在当今的大多数CPU中,数字(int)的文字(默认数据类型)大于8-bit(通常是32-bit),因此在您申请时

It is because of the literal (default data type) for a number (int) is, in most of nowadays CPU, greater than 8-bit (typically 32-bit) and thus when you apply

69 << 8 //note 69 is int

它实际上是这样应用的

00000000 00000000 00000000 01000101 << 8

因此您得到结果

00000000 00000000 01000101 00000000

如果您专门使用unsigned char,则不会发生:

If you use, say, unsigned char specifically, then it won't happen:

unsigned char a = 69 << 8; //resulting in 0

这是因为尽管69 << 8本身仍会导致

This is because though 69 << 8 itself will still result in

01000101 00000000

但是上面的值将被强制转换为8-bit unsigned char,从而导致:

But the above value will be casted to 8-bit unsigned char, resulting in:

00000000

这篇关于所有8位按位移位会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆