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 ?
To convert a string of bits into a long, you can use
Long.parseLong:You can then use the bit-shifting operators
>>,<<, and>>>to drop off the lower bits. For example:To drop off all but the top two bits, you can use
Long.bitCountto count the bits, then shift off the remaining bits.EDIT: Since the question you’re asking has to do with going from
longs to the bits of the longs, you should use theLong.toBinaryStringmethod for this:From there, to drop off the last two bits you can use simple string manipulation. Try using
String.substringfor this.Hope this helps!