Search code examples
cbit-shift

Left shift operator in C


Consider:

#include <stdio.h>
#define macro(a) a=a<<4;

main()
{
    int a = 0x59;
    printf("%x", a);
    printf("\n");
    macro(a)
    printf("%x", a);
}

For the above code, I am getting the below output:

59
590

Why am I not getting the below output as the left shift operation?

59
90

Solution

  • Left shifts do not truncate the number to fit the length of the original one. To get 90, use:

    (a<<4) & 0xff
    

    0x59 is an int and probably on your platform it has sizeof(int)==4. Then it's a 0x00000059. Left shifting it by 4 gives 0x00000590.

    Also, form a good habit of using unsigned int types when dealing with bitwise operators, unless you know what you are doing. They have different behaviours in situations like a right shift.