简体   繁体   中英

Hexadecimal unicode in c with printf()

this is my code:

#include <stdlib.h>
#include <stdio.h>

int main(int argc,char **argv){
    printf("%x\n",*argv[1]);
    return 1;
}

after compile (gcc -o main main.c) , i run it and with no problem:

./main 1
31

note: 31 is hex code of 1

but when run it with Unicode parameter, print 4Byte of hex:

./main $(printf "\Udbb1")
ffffffed

what is problem?

There are two things at play here:

The first is that when you pass an argument to a variable-argument function like printf it might be promoted . What happens here is that the character is promoted to an int value.

And here the other thing comes in, namely sign extension . If you convert a small signed type (like char seems to be on your system) to another larger signed type (like int ), if the smaller type is negative then the larger type has to be the same negative number. And because of the way two's complement (which is the most common to handle negative numbers on binary systems) works the value will be filled up with leading binary ones.

If you want to print only the char value you need to use the printf format prefix hh as in "%hhx" . The value will then be treated as an unsigned char .

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