为什么十六进制数字会自动转换为十进制? [英] Why are hexadecimal numbers automatically converted to decimal?

查看:119
本文介绍了为什么十六进制数字会自动转换为十进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个小的Python方法,该方法需要从另一个表示键和值的文件中读取字典.

I am working on a little Python method that needs to read a dictionary from another file that will represent the key and values.

但是似乎我发送的数字值的表示遇到了问题.例如,我字典中的某些键如下所示:

But it seems I am running into a problem with the representation of the number values that I am sending over. For example, some keys in my dictionary would look like this:

id_dict = {
    'val_a': 0x0000,
    'val_b': 0x1000
}

但是我注意到,当我尝试遍历字典时,十六进制将替换为十进制值.即使在字典所在的原始 id_dict.py 中,数字也会自动从十六进制转换.

But I noticed that when I attempt to iterate through the dictionary, the hexadecimal is replaced with the decimal value. Even in the original id_dict.py, where the dictionary is located, the numbers are converted from hex automatically.

这是我尝试遍历的结果:

This is my result of trying to iterate through it:

for k,v in id_dict.items():
    print(k,v)

#Results
val_a 0
val_b 4096

有人可以告诉我为什么值以原始存储的十进制而不是十六进制的形式表示吗?

Can someone tell me why the values are being represented in decimal form and not in the hexadecimal form that they are originally stored in?

如果有一种方法可以停止自动转换,那么也很容易理解!

And if there is a way to stop the automatic conversion, that would be great to understand as well!

推荐答案

有人可以告诉我为什么值以原始存储的十进制而不是十六进制的形式表示吗?

Can someone tell me why the values are being represented in decimal form and not in the hexadecimal form that they are originally stored in?

它们最初不是以十六进制存储的.Python不会跟踪有关base的任何信息;无论您在源代码中键入 0x1000 还是 4096 ,它都是相同的数字,而Python用相同的方式存储它.

They were not originally stored in hexadecimal. Python does not track any information about base; whether you type 0x1000 or 4096 in your source code, it's the same number, and Python stores it the same way.

Python打印数字时,必须选择一个基数来显示它,默认值始终是十进制.如果要以不同的方式打印它,则需要指定一种不同的方式来执行字符串转换,例如 hex 函数:

When Python prints a number, it has to choose a base to display it in, and the default is always decimal. If you want to print it differently, you will need to specify a different way to perform string conversion, such as the hex function:

>>> print 0x1000
4096
>>> print hex(0x1000)
0x1000

这篇关于为什么十六进制数字会自动转换为十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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