为什么printf的衬垫8位字符到32位? [英] Why does printf pad an 8-bit char to 32-bits?

查看:121
本文介绍了为什么printf的衬垫8位字符到32位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char byte = 0xff;
printf("%lu\n", sizeof(byte)) // Output is '1'
printf("%x\n", byte); // Output is 'ffffffff'

如果字节的大小只有一个字节,那么为什么的printf()的行为好象它是四个字节?

If the size of byte is only one byte, then why does printf() behave as if it is four bytes?

推荐答案

在形式上,你的程序表现出不确定的行为:%X 格式规范期望类型的参数 unsigned int类型,但你传递一个 INT ,说明如下(帽尖@R)。这是现代二进制补码机的做法是无害的,因为int和unsigned具有兼容位布局。但同样,从技术上说,这是不确定的行为,这将是一个好主意,修复它,如的printf(%X \\ n,(无符号)字节);

Formally, your program exhibits undefined behavior: %x format specification expects an argument of type unsigned int, but you are passing an int, as explained below (hat tip @R). This is harmless in practice on modern two's-complement machines, since int and unsigned have compatible bit layouts. But again, technically, this is undefined behavior and it would be a good idea to fix it, as in printf("%x\n", (unsigned)byte);.

有关参数传递到可变参数函数的规则规定,所有的整数类型比INT小升职为int。否则,怎么会的printf 要知道,在看到%X ,无论是抢一个字节或关闭堆栈的四个字节?从标准:

The rules for passing parameters to variadic functions state that all integral types smaller than int get promoted to int. Otherwise, how would printf know, upon seeing %x, whether to grab one byte or four bytes off the stack? From the standard:

5.2.2p7:结果
  当有一个给定的参数不带参数,该参数以这样的方式接收功能,可以通过调用的va_arg (18.10)... 如果参数有整型或枚举型,是受整体促销活动(4.5),或浮点类型,是受浮点推广(4.6),参数的值在调用之前转换为升级后的类型。

5.2.2p7 :
When there is no parameter for a given argument, the argument is passed in such a way that the receiving function can obtain the value of the argument by invoking va_arg(18.10)... If the argument has integral or enumeration type that is subject to the integral promotions(4.5), or a floating point type that is subject to the floating point promotion(4.6), the value of the argument is converted to the promoted type before the call.

这是你的字符如何变成一个 INT 。这是不确定的字符是否带符号,但显然,在平台上使用它是一个符号类型。因此,它得到的时候晋升为 INT 符号扩展。 0xFF的(炭)-1 为0xffffffff (INT)-1

This is how your char turns into an int. It's unspecified whether char is signed or unsigned, but apparently, on the platform you use it's a signed type. So it gets sign-extended when promoted to int. 0xff is (char)-1, and 0xffffffff is (int)-1.

这篇关于为什么printf的衬垫8位字符到32位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆