python 核心数_Python hex()

python 核心数

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”.

Python hex()函数用于将整数转换为以“ 0x”为前缀的小写十六进制字符串。

We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer.

我们还可以将一个对象传递给hex()函数,在这种情况下,该对象必须定义返回整数的__index__()函数。

The input integer argument can be in any base such as binary, octal etc. Python will take care of converting them to hexadecimal format.

输入的整数参数可以是任何基数,例如二进制,八进制等。Python将负责将它们转换为十六进制格式。

Python hex()示例 (Python hex() example)

Let’s look into some simple examples of converting integer to hexadecimal number.

让我们看一些将整数转换为十六进制数的简单示例。

print(hex(255))  # decimal
print(hex(0b111))  # binary
print(hex(0o77))  # octal
print(hex(0XFF))  # hexadecimal

Output:

输出:

0xff
0x7
0x3f
0xff

带有对象的Python hex() (Python hex() with object)

Let’s create a custom class and define __index__() function so that we can use hex() function with it.

让我们创建一个自定义并定义__index __()函数,以便我们可以对其使用hex()函数。

class Data:
    id = 0

    def __index__(self):
        print('__index__ function called')
        return self.id


d = Data()
d.id = 100

print(hex(d))

Output:

输出:

__index__ function called
0x64
GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22902/python-hex

python 核心数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值