Left shift operator in C

Left shifts does 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.


You shifted a hexadecimal number by 4 places to left so you get 590, which is correct.

you had

000001011001    

shifted to left by 4 bits

010110010000

is 590 in hex

10010000

is 90 in hex so you might want to remove 0101 as is shown by phoeagon


In your printf if you change %x to %d you get a =89 and after left shifting you will get a = 1424

Generally for decimal (base 10) numbers

a = a<< n  is  a = a*2^n
a = a>> n  is  a = a/2^n

For Hexadecimal (base 16) numbers ,

Any shift by n (left or right) , can be considered , as a corresponding shift of the digits of the binary equivalent. But this depends on sizeof(int) , used for a given compiler.

Tags:

C

Bit Shift