Mihir Shah
Mihir Shah

Reputation: 1809

circular bit shifting in byte array in java

How to shift one byte(8 bit shifting) to the left for 16 byte array.?

i.e. Array of 16 bytes: (0x) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

after shifting 8 bits left:

output should be: (0x) 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00

How to do this in java?

Upvotes: 0

Views: 1816

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

Here's one (not very elegant) way:

byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe};

// now shift left
byte b0 = bytes[0];
System.arraycopy(bytes, 1, bytes, 0, bytes.length -1);
bytes[bytes.length - 1] = b0;

Upvotes: 3

Related Questions