如何动C整数常量带前导零,并且怎么样的atoi? [英] How does C Handle Integer Literals with Leading Zeros, and What About atoi?

查看:309
本文介绍了如何动C整数常量带前导零,并且怎么样的atoi?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建带前导零的整数,如何Ç处理呢?它是不同版本的C有何不同?

When you create an integer with leading zeros, how does c handle it? Is it different for different versions of C?

在我的情况下,他们似乎只是被丢弃(但也许这就是printf的呢?):

In my case, they just seem to be dropped (but maybe that is what printf does?):

#include <stdio.h>

int main() {
    int a = 005;
    printf("%i\n", a);
    return 0;
}

我知道我可以用printf与0垫,但我只是想知道这是如何工作的。

I know I can use printf to pad with 0s, but I am just wondering how this works.

推荐答案

前导零表明该号码在EX pressed 或基数为8;因此,010 = 8.添加额外的前导零没有影响;正如你所期望的在数学,X + 0 * 8 ^ N = X;有通过其重新presentation不再是该值没有变化。

Leading zeros indicate that the number is expressed in octal, or base 8; thus, 010 = 8. Adding additional leading zeros has no effect; just as you would expect in math, x + 0*8^n = x; there's no change to the value by making its representation longer.

一个地方,你经常会看到这是UNIX文件模式; 0755实际上是指7 * 8 ^ 2 + 5 * 8 + 5 = 493;或使用umasks如0022 = 2 * 8 + 2 = 10。

One place you often see this is in UNIX file modes; 0755 actually means 7*8^2+5*8+5 = 493; or with umasks such as 0022 = 2*8+2 = 10.

的atoi(NPTR)被定义为等同于与strtol(NPTR,(字符**)NULL,10),但它不检测错误 - 这样,的atoi()总是使用十进制(从而忽略前导零)。 与strtol(NPTR,任何事情,0)执行以下操作:

atoi(nptr) is defined as equivalent to strtol(nptr, (char **) NULL, 10), except that it does not detect errors - as such, atoi() always uses decimal (and thus ignores leading zeros). strtol(nptr, anything, 0) does the following:

的字符串可以被任意的开始
  白色空间的数量(如确定
  通过 isspace为(3)),其次是单
  可选的+ - 标志。如果基地
  零或16,字符串可能再
  包括0X preFIX,而且数量
  将在基地16读取;否则,一个
  零基础取为10(十进制)
  除非下一个字符是 0 ,在
  这种情况下,被取为8(八进制)。

The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional '+' or '-' sign. If base is zero or 16, the string may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).

所以它使用相同的规则与C编译器。

So it uses the same rules as the C compiler.

这篇关于如何动C整数常量带前导零,并且怎么样的atoi?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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