Search code examples
cbit-manipulationbitwise-operators

convert left shifted LSB bits to 1


I need to convert LSB 0 to 1 in left shift:

x=5;
int num = 0x02;//0b00000010
shiftVal = num << x;// 0b01000000

shiftVal should convert to 0b01011111


Solution

  • Simply set them to 1 using the or operator. To get all one bits just do (1 << x) - 1

    hiftVal = (num << x) | ((1 << x) - 1);
    

    See also