bit shift - Java split the bits of a long in two parts using bit shifting -
bit shift - Java split the bits of a long in two parts using bit shifting -
i need split bits of number 9(1001
) in 2 equal sized parts 10
, 01
in case.
my first thought shift right number dont expected result ,i suspect due sign(no unsigned in java :( ).
my current code following:
long num=9; system.out.println(long.tobinarystring(num)); long num1=num>>2; system.out.println(long.tobinarystring(num1)); long num2=num<<2; system.out.println(long.tobinarystring(num2));
output:
1001 10 100100
any workaround?
to lower part, need utilize bitwise and... if shift right 2 bits higher part, need , binary number 11 (two bits 1) lower part. here's code should shift:
long num = 9; int shift = 2 system.out.println(long.tobinarystring(num)); long num1 = num >> shift; system.out.println(long.tobinarystring(num1)); long num2 = num & ( (1<<shift) - 1); system.out.println(long.tobinarystring(num2));
explanation of calculating num2
, shift
2, 0b means binary literal, in pseudocode:
( (1<<shift) - 1) == ( (1<<2) - 1) == ( 0b100 - 1) == 0b11 == 2 bits set
from should clear how work shift
value.
java bit-shift
Comments
Post a Comment