在 Python 中将十六进制字符串转换为 int [英] Convert hex string to int in Python

查看:77
本文介绍了在 Python 中将十六进制字符串转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中将十六进制字符串转换为整数?

我可能把它当作0xffff"或只是ffff".

解决方案

如果没有 0x前缀,需要明确指定基数,否则无从判断:

x = int(deadbeef", 16)

使用 0x 前缀,Python 可以自动区分十六进制和十进制.

<预><代码>>>>打印(int(0xdeadbeef",0))3735928559>>>打印(整数(10",0))10

(您必须指定 0 作为基础以调用此前缀猜测行为;如果您省略第二个参数 int() 将假设基数为 10.)

How do I convert a hex string to an int in Python?

I may have it as "0xffff" or just "ffff".

解决方案

Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:

x = int("deadbeef", 16)

With the 0x prefix, Python can distinguish hex and decimal automatically.

>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter int() will assume base-10.)

这篇关于在 Python 中将十六进制字符串转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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