简体   繁体   中英

Hexadecimal printf C programming

Can somebody explain me how does hexadecimal printfs work in this program? For example why does the first line prints 100 instead of 50?

#include <stdio.h>

 typedef struct 
 {
   int age;
   char name[20];g
 }inf;

 int main(int argc, char *argv[])
 {
     char m[]="Kolumbia",*p=m;
     int x,y;
     char* ar[]= {"Kiro","Pijo","Penda"};
     int st[] = {{22,"Simeon"}, {19,"Kopernik"}};

     x=0x80;y=2;x<<=1;y>>=1;printf("1:%x %x\n",x,y);
     x=0x9;printf("2:%x %x %x\n",x|3,x&3,x^3);
     x=0x3; y=1;printf("3:%x\n", x&(~y));

     printf("4: %c %c %s\n", *(m+1), *m+1, m+1);
     printf ("5: %c %s\n", p[3],p+3);
     printf ("6: %s %s \n", *(ar+1), *ar+1);
     printf("7: %c %c\n", **(ar+1), *(*ar+1));
     printf("8: %d %s \n",st[0].age, st[1].name+1);
     printf("9:%d %s\n",(st+1)->age,st->name+2);
     printf("10:%c %c %c\n",*(st->name),*((st+1)->name),*(st->name+1));

     return 0;
 }

In this first line containing a printf

x=0x80;y=2;x<<=1;y>>=1;printf("1:%x %x\n",x,y);

x is shifted left once, giving it the (doubled) value of 0x100 .

This is printed as 100 because the %x format does not prepend 0x .

As to why it does not print 50 I can only imagine you think that x=0x80 is assigning a decimal value which would be 50h , and also not noticed the x<<=1 .

For example why does the first line prints 100 instead of 50?

It doesn't print 100 instead of 50, but instead of 80 . Your initial value of x , given in

x=0x80;(...)
// bits:
// 1000 0000

is hexadecimal 80, 0x80, which is 128 decimal. Then you shift it by 1 to the left

(...)y=2;x<<=1;(...)

which is the same as multiply it by 2. So x becomes 256 which is hexadecimal 0x100 :

// bits:
// 1 0000 0000

And you print it in hexadecimal format which omits 0x and prints just 100 to the standard output.


You asked:

What about the "OR" operator in the second line? x=0x9;printf("2:%x %x %x\\n",x|3,x&3,x^3); 9 -> 1001 3 -> 0011, but how do we get B as a result, from what i see we need 11-> 1011 convert to hex and get B.

x=0x9;printf("2:%x %x %x\n",x|3,x&3,x^3);

Here:

x=0x9;
// 0000 1001

x|3:
// x: 0000 1001
// 3: 0000 0011
// |
// =: 0000 1011 = 0x0B , and here is your B

x&3
// x: 0000 1001
// 3: 0000 0011
// &
// =: 0000 0001 = 0x01

x^3
// x: 0000 1001
// 3: 0000 0011
// ^
// =: 0000 1010 = 0x0A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM