lifeisaloop
lifeisaloop

Reputation: 83

Bit Shift operation java - outputs to 8 bits instead of 9

So I am performing a java bit shift and then performing an XOR however, the bit shift on my string returns a string of 9 bits rather than 8.

int temp = Integer.parseInt(binary, 2);
String shift = String.format("%8s", Integer.toBinaryString(temp << 1)).replace(' ', '0');
int sum = Integer.parseInt(shiftedInput) ^ Integer.parseInt(xorConstant);

In the code above binary is a string which is "10000011" so 8 bits long. therefore temp becomes an int with the value 131, however shift has the value "100000110" which ruins the rest of my calculations. Anybody have any idea why this is? All help greatly appreciated in advance :)

Upvotes: 1

Views: 773

Answers (4)

Steve Cohen
Steve Cohen

Reputation: 4859

Why involve String formatting at all? Just because your inputs are Strings doesn't mean you need to stick with that all the way through. Just convert them to ints right away and have done with it:

int bin = Integer.parseInt(binary, 2);
int xor = Integer.parseInt(xorConstant);
int sum = (bin << 1) ^ xor;

Upvotes: 0

James Hutchinson
James Hutchinson

Reputation: 881

Use a byte instead of an int.

A byte is 8 bits. An int is 32.

    byte temp = Byte.parseByte(binary, 2);

etc.

You may need to cast when you do your shift as well.

(byte)(temp << 1)

Upvotes: 1

Loki
Loki

Reputation: 4130

As an Integer in Java has 32 bits (4Byte), your shift will return an Integer with the binary value of 00... 0001 0000 0110as you already figured out.

To get rid of the 24 bits you don't want, you can use the and operator.

((temp << 1) & 0xff)

Which returns the result you expect

       temp: 0000 0000 0000 0000 0000 0001 0000 0110
and    0xff: 0000 0000 0000 0000 0000 0000 1111 1111

     result: 0000 0000 0000 0000 0000 0000 0000 0110

Upvotes: 1

mprivat
mprivat

Reputation: 21902

Just make sure your result is confined to 8 bits or else all 32 bits of the int type are fair game:

int temp = Integer.parseInt(binary, 2);
String shift = String.format("%8s", Integer.toBinaryString((temp << 1) & 0xFF)).replace(' ', '0');
int sum = Integer.parseInt(shiftedInput) ^ Integer.parseInt(xorConstant);

Upvotes: 0

Related Questions