Search code examples
cbitbit-shift

Differences in the behavior of Bit shifting in C


I'm running a simple program to understand how bit shifting operates in C. The expression (temp << n) / 2^n is indeed equivalent to temp as I see. Reasoning this, it seems that the left shift operation effectively multiplies temp by 2^n, and then dividing by 2^n cancels out this multiplication, leaving the original value of temp. In this simple program, I get temp for n = 4 and 9 but not for n = 12. For n=12, I get 100679. Why is the behavior different for n=12? I see that we shouldnt be having any overflows for n=12 so I'm curious why this is happening.

Here is the code snippet:

#include <stdio.h>
#include <stdint.h>
#include "math.h"

int main() {
    uint32_t temp = 5343559;
    printf("%u\n", ((temp << 4)/(uint32_t)(pow(2, 4)) )); 
    printf("%u\n", ((temp << 9)/(uint32_t)(pow(2, 9)) )); 
    printf("%u\n", ((temp << 12)/(uint32_t)(pow(2, 12)) )); 

    return 0;
}

Thank you.


Solution

  • think of your number, 5343559 as its binary representation. Its declared as a unsigned 32 bit number, so it would look like this:

    00000000010100011000100101000111
    

    Notice how the most significant bit is only 9 digits from the left side. Therefore, you can only shift left by 9 until carry issues begin to occur.

    temp << 4:

    00000101000110001001010001110000
    

    temp << 9:

    10100011000100101000111000000000
    

    temp << 12

    00011000100101000111000000000000