Reputation: 3858
I have a long number and I want to manipulate it bits in following way:
Long l = "11000000011" (long l 's bit representation)
Long ll1 = "110000000" (remove last two bits from l and convert to Long)
Long ll2 = "11" (keep last two bit's of l and discard other bits and convert to Long)
Can anybody help me, how to do this in Java in a fast way ?
Upvotes: 0
Views: 2314
Reputation: 3858
long l = Long.parseLong("11110", 2) ;
long ll1 = l >>> 2;
long lb = (l & 1) ; last bit
long ls = l >>> 1;
long lb1 = (ls & 1) ; bit before last bit
Upvotes: 0
Reputation: 372694
To convert a string of bits into a long, you can use Long.parseLong
:
long l = Long.parseLong("11000000011", 2);
You can then use the bit-shifting operators >>
, <<
, and >>>
to drop off the lower bits. For example:
long ll1 = l >>> 2;
To drop off all but the top two bits, you can use Long.bitCount
to count the bits, then shift off the remaining bits.
long ll2 = l >>> (Long.bitCount(ll1) - 2);
EDIT: Since the question you're asking has to do with going from long
s to the bits of the longs, you should use the Long.toBinaryString
method for this:
String bits = Long.toBinaryString(/* value */);
From there, to drop off the last two bits you can use simple string manipulation. Try using String.substring
for this.
Hope this helps!
Upvotes: 3