Search code examples
c++bitbitset

How can i encode and decode two number in a single integer using bit manipulations?


I was learning about bit manipulations then I thought of this. Say I have two numbers, First in the range of [1,6] and second in the range of [0,3]. Now the first number can take max 3 bits to be stored and the second can take 2 bits to be stored. How can I use one int32 to store both of them in it. Thanks.


Solution

  • Encode:

    // a : range of [1,6], bit0 ~ bit2
    // b : range of [0,3], bit3 ~ bit4
    // c : encoded int32
    c = 0;
    c |= (a | b << 3);
    

    Decode:

    a = (c & 0x00000007);
    b = (c & 0x00000018) >> 3;