简体   繁体   English

位移大于32位长

[英]Bit shifting for >32 bit long

I am trying to extract the first 49 bits from a 7 byte array. 我试图从7字节数组中提取前49位。 I approached this byte using masks and bit shifting as follows: 我使用掩码和位移来处理此字节,如下所示:

long byteVal = ((decryptedVCW[6] & 0xff)&((decryptedVCW[6] & 0xff)<<7)) | ((decryptedVCW[5] & 0xff) << 8) | ((decryptedVCW[4] & 0xff) << 16) | ((decryptedVCW[3] & 0xff) << 24) | ((decryptedVCW[2] & 0xff) << 32) | ((decryptedVCW[1] & 0xff) << 40) | ((decryptedVCW[0] & 0xff) << 48);

Where decryptedVCW is a 56 bit byte array. 其中,解密的VCW是一个56位字节的数组。

The masking and bit shifting work as expected until the 32 bit shift '<<32'. 屏蔽和位移位按预期工作,直到32位移位'<< 32'。

As an example, the hex for decryptedVCW is E865037A9C6424 of which in binary is: 例如,解密的VCW的十六进制为E865037A9C6424,二进制形式为:

11101000011001010000001101111010100111000110010000100100 11101000011001010000001101111010100111000110010000100100

When I perform the above shifting I get 7AFC6503 in binary: 当我执行上述转换时,我得到二进制形式的7AFC6503:

1111010111111000110010100000011 1111010111111000110010100000011

Does anyone have any idea why the bit shifting falls apart at 32 upwards and how to go about solving this issue? 有谁知道为什么移位在32位以上会分开,以及如何解决这个问题?

Many thanks Shiv 非常感谢Shiv

The type of decryptedVCW[2] & 0xff is int , since the first operand is byte and the second is an int literal. 的类型的decryptedVCW[2] & 0xffint ,由于第一操作数是byte ,第二个是一个int字面。

When the first operand of the << operator is int , you are shifting an int , so if the second operand is 32, you'll get int overflow. <<运算符的第一个操作数为int ,您正在移动一个int ,因此,如果第二个操作数为32,则将得到int溢出。

You can cast the first operand of the << operator to long : 您可以将<<运算符的第一个操作数转换为long

(((long)(decryptedVCW[2] & 0xff)) << 32)

or you can force the first operand to be a long by using a long literal in the & operation, as suggested by @shmosel : 或者您可以通过在&操作中使用long字面量来强制第一个操作数变long ,如@shmosel所示:

(decryptedVCW[2] & 0xFFL) << 32

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM