brazjul
brazjul

Reputation: 339

Java - How to Extract Certain Portions of Bits Using Bit Mask?

This is the first time I am looking at bitwise operations and bit mask. I have seen some examples using C and C++, but I am looking for clarification using Java.

I have the following 32-bit string

0000 0000 1010 0110 0011 1000 0010 0000

But I want to extract bits 21 through 25 in bold (00101) and ignore everything else. In the end, I want my output result to be integer 5 (0101 in binary)

Using bit mask, what approach I could use to get just that bit portion as my output result?

Upvotes: 1

Views: 2891

Answers (1)

Chai T. Rex
Chai T. Rex

Reputation: 3020

If you really have a String, take the two substrings (00 and 101), concatenate them, and use Integer.parseInt with a radix of two:

int bits = Integer.parseInt(str.substring(7, 9) + str.substring(10, 13), 2);

If you have an int, use a logical right shift, then use & with a bit mask (0b signifies binary notation).

int bits = (n >>> 21) & 0b11111;

Upvotes: 4

Related Questions