使用python脚本将十六进制、八进制数转换为十进制形式
有许多 inbulit 函数,如 int(octal) ,可用于在命令行上将八进制数转换为十进制数,但这些在 script 中不起作用。 int(0671) 在脚本中返回 0671,它代表 python 命令行中八进制数的十进制形式。 帮助???
谢谢
There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script .
int(0671) returns 0671 in script, where as it represent decimal form of octal number on python command line.
Help???
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,int() 没有用。您只需输入 0671 即可。
然后,该数字以二进制形式存储在计算机本身上,您只需转换其字符串表示形式即可。数字本身不会改变。因此,这两个值都将解析为 True,例如,这可能是混乱的根源:
为了确保程序能够输出所需基数中的数字,最简单的方法是使用字符串格式,例如所以(如果你希望它以 10 为基数):
First, the int() is useless. You can just type 0671.
Then, the number is stored in binary on the computer itself, you are only converting its string representation. The number itself doesn't change. Therefore, both of these will resolve to True, for example, which might've been the source of confusion:
To ensure you will get the program to output the number in the base you want, the simplest way is to use string formatting, like so (if you want it to be in base 10):
这里有一些混乱——迂腐地(对于计算机来说,迂腐总是最好的;-),没有“八进制数字”,有字符串,它们是八进制表示数字(以及更常见的其他字符串,它们是十进制表示形式、十六进制表示形式)。底层数字(整数)是与任何表示形式完全不同的类型(默认情况下显示它们的十进制表示形式)——例如:
引号表示字符串(即表示形式)——并且请注意,它们本身没有任何内容与它们可能代表的数字有关。
因此,解释您的问题的一种方法是您想要将八进制表示形式转换为十进制表示形式(等等)——那就是:
注意引号(表示字符串,即表示形式)。
int(s, 8)
将字符串s
转换为八进制表示形式的整数(如果转换失败,则引发异常)。str(n)
生成数字n
的字符串形式(正如我提到的,默认情况下是十进制表示形式)。There's some confusion here -- pedantically (and with computers it's always best to be pedantic;-), there are no "octal numbers", there are strings which are octal representations of numbers (and other strings, more commonly encountered, which are their decimal representations, hexadecimal representations). The underlying numbers (integers) are a totally distinct type from any of the representations (by default their decimal representation is shown) -- e.g.:
the quotes indicate strings (i.e., representations) -- and note that, per se, they have nothing to do with the numbers they may be representing.
So, one way to interpret your question is that you want to convert an octal representation into a decimal one (etc) -- that would be:
note the quoted (indicating strings, i.e., representations).
int(s, 8)
converts the strings
into an integer as an octal representation (or raises an exception if the conversion can't work).str(n)
produces the string form of numbern
(which, as I mentioned, is by default a decimal representation).