python字符串转16进制_在python中将字符串转换为十六进制

1586010002-jmsa.png

I have a script that calls a function that takes a hexadecimal number for an argument. The argument needs to the 0x prefix. The data source is a database table and is stored as a string, so it is returned '0x77'. I am looking for a way to take the string from the database and use it as an argument in hex form with the 0x prefix.

This works:

addr = 0x77

value = class.function(addr)

The database entry has to be a string, as most of the other records do not have hexadecimal values in this column, but the values could be changed to make it easier, so instead of '0x77', it could be '119'.

解决方案

Your class.function expects an integer which can be represented either by a decimal or a hexadecimal literal, so that these two calls are completely equivalent:

class.function(0x77)

class.function(119) # 0x77 == 119

Even print(0x77) will show 119 (because decimal is the default representation).

So, we should rather be talking about converting a string representation to integer. The string can be a hexadecimal representation, like '0x77', then parse it with the base parameter:

>>> int('0x77', 16)

119

or a decimal one, then parse it as int('119').

Still, storing integer whenever you deal with integers is better.

EDIT: as @gnibbler suggested, you can parse as int(x, 0), which handles both formats.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值