Search code examples
c++c++14bit-manipulationbitwise-operators

getting specific k bits from a Decimal number


I have a number x and I want to print decimal of k bits from x suppose I have number 12 x = 12 k = 3 binary of 12 is 1100 and k =3 so my resulting new binary will be 100(decimal is 8) ie form last position I want to display 8 as output

I want to do this with help of << and >> in c++ Thanks!!


Solution

  • Here is one way of doing it: zero out the last k bits, then subtract that from x.

    unsigned int last_k_bits(unsigned int x, unsigned int k) {
        return x - ((x >> k) << k);
    }
    

    You can also calculate the bitwise & of x and 1...1 (k 1s)

    unsigned int last_k_bits(unsigned int x, unsigned int k) {
        return x & ((1u << k) - 1);
    }
    

    Also, 100 is 4 in decimal, not 8