Shifting negative BigInteger value - Java

試著忘記壹切 提交于 2019-12-13 05:13:23

问题


I am trying to shift a 7 byte array to the right by 7 bits.

To do this, I am using BigInteger's shiftright method. However, when shifting right for negative BigIntegers, padding with 1s are added or sometimes the leading bit is removed.

Here is the following bit of code doing the shifting:

byte[] vcwManD = decryptedVCW;
BigInteger bigIntD = new BigInteger(vcwManD);       // create big int array for shift
BigInteger shiftIntD= bigIntD.shiftRight(7);                // shift right 7 bits
vcwManD = shiftIntD.toByteArray();      

For a byte array E865037A9C6424 in binary:

11101000011001010000001101111010100111000110010000100100

When shifted I get D0CA06F538C8 in binary:

110100001100101000000110111101010011100011001000

As you can see, it has shifted 7 bits to the right, however the leading bit has been stripped.

Another issue is the 1 padding. For byte array 90998951A37908 in binary

10010000100110011000100101010001101000110111100100001000

produces FF213312A346F2 in binary:

11111111001000010011001100010010101000110100011011110010

This time around 7 1's have been padded at the start.

Does anyone know how to solve this issue?

Many thanks Shiv


回答1:


If you are doing bit shifts you are likely working with a long unsigned value rather than signed value. So when you create your BigInteger use this constructor:

new BigInteger(1, vcwManD);

That way you are guaranteed to have a positive number and you should be able to shift it around with no consequence.




回答2:


Negative numbers are stored in memory using two's complement. This means that if the number is negative, the first bit will be 1. When you bit shift a negative number to the right, it must remain negative, so the newly introduced values will be 1's.



来源:https://stackoverflow.com/questions/34753668/shifting-negative-biginteger-value-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!