首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符串转换为十六进制

将字符串转换为十六进制
EN

Stack Overflow用户
提问于 2015-04-07 15:04:38
回答 2查看 275关注 0票数 0

我有一个字符串文件,但其中的字符串表示十六进制值。例如,我的文件中有这样的字符串:

代码语言:javascript
复制
1091    A3B7    56FF    ...

我不想将它们用作字符串,而是用作十六进制值;然后将十六进制转换为int。

例如:

1091(in string)---> 1091(in hexa)---> 4241 # The int value of 1091 in hexa

所以我上网看了看。我尝试了很多不同的方法,比如:

  1. https://stackoverflow.com/questions/12214801/print-a-string-as-hex-bytes
  2. https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python

但没有任何东西与我所需要的完全相符,或者根本不起作用。

这是我代码的一部分:

代码语言:javascript
复制
t = False
i = 0
while t != True and h != True or i <=100: # My way to look each string of my file
    file = row[1]
    read_byte = file[i]

    if read_byte == 'V': #V is the letter in my file which says that it s the data that I want then there is 2 kinds of channel 01 and 02 that interest me

        i=i+1
        a=i+2
        read_bytechannel = file[i:a]  #read 2 strings because the channel can be '01' or '02'

        if read_bytechannel == '01':
            print(read_bytechannel)
            i=i+1
            a=i+4
            read_bytetemp = file[i:a] # Reading 4 strings because the value is the int value of the two hexa.
            realintvalue= # (?????????convert the read_bytetemp string value into an hexa value, then into an int from the hexa)

            tempfinal = realintvalue/100 # I have to divide by 100 the int value to get the real temperature
            t = True # This condition just tell me that I already know the temporary

    i = i+1

这是我想读的那种文件:

代码语言:javascript
复制
@
I01010100B00725030178
V01109103
I02020100B00725030148
V0215AA5C
$
@
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-07 15:06:32

代码语言:javascript
复制
>>> int('1091', 16)
4241

int的第二个参数是解释第一个参数的基础。

票数 1
EN

Stack Overflow用户

发布于 2015-04-07 15:13:10

您可以尝试这样的方法,带基数为16的int:

代码语言:javascript
复制
>>> my_string = "1091 A3B7 56FF"
>>> map(lambda x:int(x,16), my_string.split())
[4241, 41911, 22271]

或者你可以两者兼得:

代码语言:javascript
复制
>>> map(lambda x:[x,int(x,16)], my_string.split())
[['1091', 4241], ['A3B7', 41911], ['56FF', 22271]]

如果您对lambdamap不满意,可以使用列表理解。

代码语言:javascript
复制
>>> [[x,int(x,16)] for x in my_string.split()]
[['1091', 4241], ['A3B7', 41911], ['56FF', 22271]]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29494846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档