Search code examples
c64-bitbit-shift32-bitfixed-point

Right shift operation on 32 bit variable


I want to do right shift of 33 on a 32 variable and store the result into a float variable.

For suppose, the value is 1717986812. When we right shift by 33, we expect the value to be 0.2.

But when I do 1717986812 / (1<<33), I am getting some other huge integer value. I know that the result of 1<<33 can't be stored in a 32-bit value. So, I tried 17917986812 / (1UL<<33), but didn't get the correct results. I believe, something needs to be done regarding format conversions. But, couldn't figure it out.


Solution

  • For suppose, the value is 1717986812. When we right shift by 33, we expect the value to be 0.2.

    Wait wait? No? Bit shifting is an integer activity, so a floating-point result to appear would be very magical. Shifting an integer right by more bits that the entire integer consists of, would "logically" result in 0, but in C it happens to be undefined.

    If you want to divide a floating point value, just do so:

    float x = 1717986812;
    x /= powf(2, 33);
    printf("got %g\n", x);
    

    This printed 0.2 when I tested it online.