C printf%d前导零是否正确? [英] C printf %d incorrect value with leading zeros?

查看:151
本文介绍了C printf%d前导零是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C函数printf似乎根据是否存在前导零而打印不同的值。

The C function printf seems to print different values depending on whether or not leading zeros are present.

我试图确定其中的mode参数的数值


printf( mode:%d\n,S_IRWXU);

printf( mode:%d\n,00700);

I was trying to determine the numerical values for the mode argument in the Linux 'open' system call.

printf("mode:%d\n",S_IRWXU);
printf("mode:%d\n",00700);

都给了我448 ,而

both gave me 448, while

printf( mode:%d\n,700); 给了我700,正如我期望的那样。

printf("mode:%d\n",700); gives me 700, as I would expect from both.

这是怎么回事?

我正在使用gcc(Ubuntu 5.4.0-6ubuntu1〜16.04.5)5.4.0 20160609

I am using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609

推荐答案

一个数值常量带有一个或多个前导零的是一个八进制常数,而没有一个前导零的一个是一个十进制常数,而一个带有前导的 0x 十六进制常量。在任何情况下,无论将值传递给 printf 还是任何其他函数,都适用。

A numerical constant with one or more leading zeros is an octal constant, while one without a leading zero is a decimal constant and one with a leading 0x is a hexadecimal constant. This holds in any context, whether the value is passed to printf or any other function.

printf ,您正在使用%d 格式说明符,该说明符以十进制打印值。如果您输入八进制常量,则会看到该八进制数字的十进制值。在此示例中,0700b8 == 7 * 8 ^ 2 + 0 * 8 ^ 1 + 0 * 8 ^ 0 == 7 * 64 == 448b10

In the case of printf, you're using the %d format specifier which prints the value in decimal. If you pass in an octal constant, you'll see the decimal value of that octal number. In this example, 0700b8 == 7 * 8^2 + 0 * 8^1 + 0 * 8^0 == 7 * 64 == 448b10

在处理文件权限时,这些值通常表示为八进制,因此您应始终在这些值前使用0开头。

If you're dealing with file permissions, those values are typically denoted as octal, so you should always use a leading 0 with those.

这篇关于C printf%d前导零是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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