Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

bit manipulation - Obtain a specific subset of bits of an int in Java

How would I obtain a specific subset, say bits 5-10, of an int in Java?

Looking for a method where one can pass in specific bit positions. I'm not sure how I would create a mask that changes given the input, or even if that is how one should go about doing it.

I know this is how one would get the front say 10 bits of an int: (I think) int x = num >> 22;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Say you have a number n, and want bits from i to j (i=5, j=10).

Note, that i=0 will give you the last bit

 int value = n & (((1 << (j-i)) - 1) << i );

will give you the result.

The left part is obvious: you have a value, and you will put a bitmask on it.

The value of the mask is ((1 << (j-i)) - 1) << i. It says:

  • Take a 1 bit (value: 0000000000000001)
  • Shift it left j-i times (value: 2^(10-5) = 2^5 = 32 = 0000000000100000)
  • Deduct 1 (value: 31 = 0000000000011111) - have you seen the lowest bits reversed?
  • Shift it left i times (value: 31*32=992 = 0000001111100000)

So, you have got the bitmask for bits 5 - 10 (more precisely, from 5 to 9, since 10th is not included).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...