问题
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