How to shift bits across array of ints

0

Alright, I'll keep this plain & simple.

I'm working on a brute implementation of SHA-256 in Java, and to keep the class methods conducive to other classes in the app, I've decided to I/O the data as an array of 32-bit integers (int). Obviously, these kinds of uses rely heavily on use of bitwise operators, so how do I accomplish bitwise shifting across an array of ints, as such:

Given an array of data, suppose:

 int[16] data;

where the first 14 integers' worth of data is filled with 0x0000000, for the purposes of conversation, but the lowest two are filled respectively:

 data[14] = 0x12345678;
 data[15] = 0x01ABCDEF;

How do I accomplish a leftwise shift so that if shifted left by two,

 data[13] = 0x00000012;
 data[14] = 0x34567801;
 data[15] = 0xABCDEF00;

Anyone got any ideas?

java
int
bit-manipulation
shift
sha256
asked on Stack Overflow Nov 16, 2013 by ecfedele

2 Answers

0

1) Write a helper method to convert your int[16] data to byte[64] bytedata.

2) Create a BigInteger using the constructor BigInteger(byte[] val)

3) Bitshift using shiftLeft(int n) and shiftRight(int n)

4) Write a helper method to convert your byte[64] bytedata back to int[16] data. See byte array to Int Array here

Other useful methods in BigInteger include clearBit(int n), setBit(int n), flipBit(int n), and testBit(int n)

answered on Stack Overflow Nov 16, 2013 by Ron • edited May 23, 2017 by Community
-1

For bitwise shift left:

`x << n` is the same as `x *= 2^n`  

To see the overflowing bit (MSB): x / (2^32) >= 1 //Since we are using an 32 bit int


Likewise, for bitwise shift right:

`x >> n` is the same as `x /= 2^n`  

To see the overflowing bit (LSB): x % 2

Append the overflowing bit to the adjacent int by adding or subtracting set values. You should really use a BigInteger like I mentioned in my comment, anything else will require an implementation where you read and append the bits moving between array locations yourself.

answered on Stack Overflow Nov 16, 2013 by Ron • edited Nov 18, 2013 by Ron

User contributions licensed under CC BY-SA 3.0