Reputation: 3389
I need to split the bits of a number say 9(1001
) in two equal sized parts 10
and 01
in this case.
My first idea was to just shift it but for the right number I dont get the expected result ,I suspect this is due to the sign(no unsigned in java :( ).
My current code is the 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?
Upvotes: 0
Views: 1070
Reputation: 62906
To get the lower part, you need to use bitwise AND... so if you shift right by 2 bits to get the higher part, you need to AND with binary number 11 (two bits as 1) to get the lower part. Here's code which should do it for any 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
, for shift
2, 0b means binary literal, in pseudocode:
( (1<<shift) - 1) == ( (1<<2) - 1) == ( 0b100 - 1) == 0b11 == two bits set
From that it should be clear how it will work for any shift
value.
Upvotes: 1
Reputation: 30446
You could shift num1
back 2 and the subtract it from num
. This will give you num2
.
Upvotes: 1