printf字节到十六进制字符串奇怪输出

abi*_*alg 2 printf hex

以下简单代码产生奇怪的输出:

#include <stdio.h>
#include <string.h>
#include "/tmp/sha.h"
#define DIGEST 64

//taken from coreutils 8.5 - produces 64-byte sha digest and puts it into resblock
extern int sha512_stream(FILE *stream, void *resblock);

int main(int argc, char** argv) {

char sha[DIGEST];
memset(sha, 0, DIGEST);
FILE *stream;
stream = fopen("/bin/less", "r");
sha512_stream(stream, (void *) sha);
fclose(stream);

char buf[2] = {10, 32};
printf("%02x\n", sha[0]);
printf("%02x\n", buf[0]);

return 0;}
Run Code Online (Sandbox Code Playgroud)

给出输出:
ffffffa9
0a

sha的第一个字节是A9,但填充F来自何处?

在Ubuntu Linux 10.10上使用gcc 4.4.5.

gee*_*aur 7

(char)默认为(signed char)在Linux x86,并且因为printf()使用stdarg(signed char)被隐式地提升为(int)导致符号扩展.您需要声明它(unsigned char)以获得预期的行为.(无法传递类型信息stdarg,因此对参数执行默认促销.)