在 printf 语句中使用 %x 打印整数数据类型的值

Printing the value of integer data type using %x in printf statement

被下面的一段代码弄糊涂了。

#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}

我得到的值是 40。

谁能给我解释一下这是怎么回事?

注意:当我删除数字 1 之前的数字 0 时,当 100 转换为十六进制时,它的 64 是正确的。

Codepad link to above code

这里

int a=0100;

您正在分配一个 八进制 值,该值以 10 为基数为 64,十六进制为 40。

0 开头的整数文字在 C 语言中是八进制的。

c 中的 0 前缀表示八进制,而不是十进制。

http://en.cppreference.com/w/cpp/language/integer_literal

  • decimal-literal is a non-zero decimal digit (1, 2, 3, 4, 5, 6, 7, 8, 9), followed by zero or more decimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • octal-literal is the digit zero (0) followed by zero or more octal digits (0, 1, 2, 3, 4, 5, 6, 7)
  • hex-literal is the character sequence 0x or the character sequence 0X followed by one or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F)
  • binary-literal is the character sequence 0b or the character sequence 0B followed by one or more binary digits (0, 1)

在 C 语言中,以 0 为前缀的常量是 八进制 常量。基数 8 中的 0100 是 1000000 以 2 为基数,十六进制为 40,以 10 为基数为 64。因此您的程序正在打印它应该打印的内容。

0100 是一个八进制值,因为它有前缀 0

0100 in octal (base 8)
 ^~~~(8^2)*1

is same as  

0x40  in hexadecimal (base 16)
  ^~~~(16^1)*4   // %x is for hexadecimal format

is same as 

64 in decimal (base 10)

printf("%o %x %d",a, a, a);  // prints 100 40 64