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

时间:2011-06-21 17:10:39

标签: hex printf

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

#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;}

给出输出:
ffffffa9
0a

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

在Ubuntu Linux 10.10上使用gcc 4.4.5。

1 个答案:

答案 0 :(得分:7)

在Linux x86上,

(char)默认为(signed char),由于printf()使用stdarg(signed char)会被隐式提升为(int),从而导致签署延期。您需要声明它(unsigned char)以获得预期的行为。 (无法通过stdarg传递类型信息,因此会对参数执行默认促销。)

相关问题