Search code examples
bit-manipulationhlsl

Flipping bits in an integer without bitwise operations


I need to flip the bits in an integer from 1 to 0 and 0 to 1. E.g 10010 to 01101. The problem is that in HLSL ps_3_0 there are no binary operators. No ~, <<, >>,...

Is there a mathematical way of accomplishing this?


Solution

  • You can use the following solution

    int inverse(int x)
    {
        return 0xFFFFFFFFU - x;
    }
    

    otherwise:

    int inverse(int x)
    {
        return -x - 1; // because -x = ~x + 1, only works in 2's complement
    }