位超过8位移位字节 [英] Bit shifting a byte by more than 8 bit

查看:159
本文介绍了位超过8位移位字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

rel=\"nofollow\">
当从字节转换缓冲器回unsigned long int类型:

In here When converting from bytes buffer back to unsigned long int:

  unsigned long int anotherLongInt;

  anotherLongInt = ( (byteArray[0] << 24) 
                   + (byteArray[1] << 16) 
                   + (byteArray[2] << 8) 
                   + (byteArray[3] ) );

在这里的字节数组被声明为 unsigned char型的字节数组[4];

问:

我觉得的字节数组[1] 将只是一个无符号字符(8位)。 16当左移,那不是所有的有意义的位出移位和0填充整个字节?显然,这不是的8位。也许是移动整个的字节数组这是一个连续的4个字节?但我不明白是如何工作的。

I thought byteArray[1] would be just one unsigned char (8 bit). When left-shifting by 16, wouldn't that shift all the meaningful bits out and fill the entire byte with 0? Apparently it is not 8 bit. Perhaps it's shifting the entire byteArray which is a consecutive 4 byte? But I don't see how that works.

推荐答案

在算术方面的 的字节数组[0] 晋升 INT unsigned int类型,这样的转变是合法的,甚​​至懂事(我想只能用<$ C $处理C>无符号类型做按位的东西的时候)。

In that arithmetic context byteArray[0] is promoted to either int or unsigned int, so the shift is legal and maybe even sensible (I like to deal only with unsigned types when doing bitwise stuff).

6.5.7按位移位运算符

6.5.7 Bitwise shift operators

整数促销活动在每个操作数执行。该结果的类型是,促进左操作数。

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.

和整数优惠:

6.3.1.1

如果int可以重新present原始类型的值转换为int的所有值;
  否则,将其转换为一个unsigned int。这些被称为的整数促销

If an int can represent all values of the original type the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

这篇关于位超过8位移位字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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