Left shift operator in c

#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 get the following output:

59 590

And now my question is: why am I not getting the bottom output as a left shift operation:

59 90

+5
source share
5 answers

Left shifts do NOT crop the number corresponding to the length of the original. To get 90, use:

(a<<4) & 0xff

0x59- this is int, and probably is on your platform sizeof(int)==4. Then this is a 0x00000059. A left shift of 4 gives 0x00000590.

Also, create a good habit of using types unsigned intwhen working with bitwise operators if you don't know what you are doing. They have different behaviors in situations similar to right shifts.

+7
source

4 , 590, .

000001011001    

4

010110010000

590

10010000

90 , 0101, phoeagon

+6

printf, % x % d a = 89 a = 1424

( 10)

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

( 16) ,

n ( ) . sizeof (int), .

+3

int, :

 000001011001  

4 , :

010110010000

8 , "int", char ( char)

#include<stdio.h>
#define macro(a) a=a<<4;
main()
{
   unsigned char a=0x59;
   printf("%x",a);
   printf("\n");
   macro(a)
   printf("%x",a);            
}

int, 8 , :

#define macro(a) a=(a<<4) & 0xFF
+1

Could you tell me what to do to get the result as 90..i you need to shift the last 4 bits to the first 4 bits , adding 0 at the end

The only way to shift the last 4 bits is 4 bits to the left AND get it instead of the first 4 bits if your type has only 8 bits. This usually matters unsigned char, not int. You expect 90for

unsigned char a=0x59;
macro(a)

but for intthere is a 590 mistake is not to use <<with the choice of type. (or a skip macro?)

-1
source

All Articles