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

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

问题描述

我有一个脚本调用一个函数,它为参数提供一个十六进制数字。该参数需要0x前缀。数据源是一个数据库表,并作为字符串存储,因此返回'0x77'。我正在寻找一种方法从数据库中获取字符串,并将其用作带有0x前缀的十六进制格式的参数。



这适用于:

  addr = 0x77 
value = class.function(addr)

数据库条目必须是字符串,因为大多数其他记录在此列中没有十六进制值,但可以更改这些值以使其更容易,所以改为'0x77',它可能是'119'。

解决方案

class.function 需要一个可以用十进制或十六进制文字表示的整数,以便这两个调用是完全等同的:

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

即使 print(0x77)也会显示 119 (因为十进制是默认表示)。



所以,我们应该谈论co将字符串表示颠倒为整数。该字符串可以是十六进制表示,如'0x77',然后用基本参数解析它:

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

或者一个小数,然后解析它作为 int('119')



然而,每当处理整数时都存储整数更好。 int(x,0),它可以处理这两种格式。 $ b / p>

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.

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

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