KornShell: Variable assigned “000010” converted to 8 instead of 10.

删除回忆录丶 提交于 2020-01-06 04:51:14

问题


I have a fixed length string which is a number. When I assign the string to a variable it is getting assigned 8 instead of 10. Why? How do I stop it?

$ i=10
$ ((i=i+1))
$ echo $i
11    # Right answer
$ i=000010
$ ((i=i+1))
$ echo $i
9     # Wrong answer

Update: The answers confirm that the number is being converted to octal and that the leading zeros need to be removed. Here is the sed command for that.

echo "000010" | sed 's/0*//'


回答1:


That's because a leading 0 means that the constant is octal (base 8) instead of decimal (base 10). To stop it, you need to strip off the leading 0s




回答2:


Korn shell interprets numbers starting with zero as octal.




回答3:


A leading zero on a number (in C, C++, C# et al) means "this is an octal constant" and (oct) 10 == (dec) 8.




回答4:


This will strip leading zeros without resorting to spawning sed (at least in ksh93):

$ i=000010
$ i=${i/#*(0)}
$ ((i++))
$ echo $i
11

The same thing works in Bash if you have extended globbing turned on (shopt -s extglob).

Edit:

You can also force the value to be interpreted as base-10:

$ i=000010
$ ((i = 10#$i + 1))
$ echo $i
11



回答5:


What you write here:

$ i="0888"   # 888 with a leading zero.
$ echo ${i}
888          # Is fine.

$ i="000010"
$ echo ${i}
8            # This returns 8 however.

cannot be true. Interpretation of numeric literals only takes place inside arithmetic expansion (i.e. double parens). Otherwise 0888 is just an ordinary string and if shell would strip the leading zero or convert the number to some other base it would be an awful bug. Just checked in the Korn shell:

$ i="0888"
$ echo ${i}
0888
$ i="000010"
$ echo ${i}
000010

$ ksh --version
  version         sh (AT&T Research) 93s+ 2008-01-31


来源:https://stackoverflow.com/questions/3190147/kornshell-variable-assigned-000010-converted-to-8-instead-of-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!