简体   繁体   English

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

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

Got confused with the following peice of code. 与以下代码混淆了。

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

The value I am getting is 40. 我得到的值是40。

Can someone explain me whats going on here? 有人可以解释一下这是怎么回事吗?

Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex. 注意:当我在数字1之前删除数字0时,那么当100转换为十六进制时,它即将到来的64是正确的。

Codepad link to above code 键盘链接到上面的代码

In C, a constant prefixed with a 0 is an octal constant. 在C中,以0 开头的常量是八进制常量。 0100 in base 8 is 1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should. 基数8中的0100在基数2中为1000000,在十六进制数中为40,在基数10中为64。因此,您的程序正在精确地打印应有的内容。

Here 这里

int a=0100;

you are assigning an octal value, which is 64 in base 10 and 40 is hex. 您正在分配一个八进制值,即以10为底的64,十六进制为40。

An integer literal starting with a 0 is octal in C. 0开头的整数文字在C中为八进制。

a 0 prefix in c means octal, not decimal. c中的0前缀表示八进制,而不是十进制。

http://en.cppreference.com/w/cpp/language/integer_literal 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) 十进制数字是一个非零的十进制数字(1、2、3、4、5、6、7、8、9),后跟零个或多个十进制数字(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) 八进制字母是数字零(0),后跟零个或多个八进制数字(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) hex-literal是字符序列0x或字符序列0X,后跟一个或多个十六进制数字(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) 二进制字面量是字符序列0b或字符序列0B,后跟一个或多个二进制数字(0,1)

0100 is a octal value as it has prefix 0 . 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM