c - 在 C 中 printf() 中将 int 类型转换为 char

标签 c casting

int *int_pointer = malloc(10);

*int_pointer = 53200;

printf("The integer at byte #0 is set to: %d \n", (char) *int_pointer);

结果:-48

所以我只是尝试一下,看看会发生什么,我得到了这个非常意想不到的结果。

为什么是-48?怎么变成负数了?

最佳答案

语言律师视角:

我相信 C99/C11 标准中的正确引用是 §6.3.1.3 (重点是我的):

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
  3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

请注意,char 类型是有问题的,因为如果它实际上表示为有符号或无符号,它也是实现定义的。标准本身完全定义的唯一方法是转换为 unsigned char 类型。

实用 View :

假设您的实现 sizeof(int) == 4 并使用二进制补码方法来存储有符号整数,则数字 53200 表示为:

0000 0000 0000 0000 1100 1111 1101 0000

请注意,如果您有小端 CPU(可能这是正确的假设),那么字节顺序,或者更严格地说它们实际存储在内存和 CPU 寄存器中的方式是相反的,即该数字存储为:

0000 1101 1111 1100 0000 0000 0000 0000

(unsigned char) 53200 生成的是(纯粹数学意义上的)减法的结果(请注意,标准保证 sizeof(unsigned char) == 1) :

53200 - 256 - 256 - ... - 256 = 53200 % 256 = 208

它是二进制的1101 0000

可以从数学上证明,结果始终与“截止”相同,仅保留最后一个最低有效字节作为强制转换的结果。

printf() 的注意事项:

正如@pmg所指出的,printf()是可变参数函数,并且由于默认参数提升,其可选参数类型为unsigned char(或signed charchar 也一样)总是提升为 int,但这一次“只是一种形式” .

替代双向运算符解决方案的注意事项:

作为替代解决方案,您可以使用带有适当掩码的双向 & and 运算符来获取特定数字的最低有效字节,例如:

*int_number & 0xff   /* mask is 0000 0000 0000 0000 1111 1111 */

关于c - 在 C 中 printf() 中将 int 类型转换为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25081572/

相关文章:

c++ - 无法从 vector<T> 转换为 T

c - 在 C 编程中的链表末尾追加一个元素

c - C标准库函数与系统调用。哪个是 `open()`?

c++ - 如何扩展词法转换以支持枚举类型?

.NET 类型转换对象

c++ - 类型转换泛型类型 C++

c - 从指针结构打印成员

c - 如何从 strace 输出中解码此信息

c - 如何在eclipse控制台中看到printf(C代码)?

java - 为什么从接口(interface)执行方法时会将参数转换为 Object(或扩展 YourObject)?