Obtain a specific subset of bits of an int in Java

后端 未结 2 2066
旧时难觅i
旧时难觅i 2020-12-11 22:57

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

相关标签:
2条回答
  • 2020-12-11 23:15

    To obtain value of bit 1 (bits are indexed from 0 to 31)

    int val = bits & 0x002;
    

    To obtain value of bit 16

    int val = bits & (1<<16);
    

    To obtain value of bit n

    int val = bits & (1<<n);
    
    0 讨论(0)
  • 2020-12-11 23:21

    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).

    0 讨论(0)
提交回复
热议问题