Search code examples
javabinarybit-manipulationbitwise-operators

How to change the most significant bit to a 1 after shifting an int to the right using '>>'?


For example, when I have a number such as 0x54 in binary that would be 01010100. After using the bit-wise operator '>>' this number will turn into 00101010. Instead of the most significant bit being a 0, I need it to be a one. How can i accomplish this?


Solution

  • Is your number always 8 bits wide? If thats the case you can simply have the decimal representation of 10000000 which is 128 and do a bitwise or so let's take your example

    int val = 84; /// 01010100
    int newVal = val >> 1; // 00101010
    int mostSig = newVal | 128; // 10101010