如何将十六进制str转换为int数组 [英] How to convert hex str into int array

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

问题描述

我有十六进制字符串,例如'01ff6fee32785e366f710df10cc542B4',我试图将它们(有效地)转换为2字符乘2字符(例如[1,255,...])的int数组.

I have strings of hex, for exemple '01ff6fee32785e366f710df10cc542B4' and I am trying to convert them (efficiently) into an int array 2 characters by 2 characters like [1,255,...].

我尝试了

c = '8db6796fee32785e366f710df10cc542B4' 
c2=[int(x,16) for x in c]

,但它只会一个接一个地输入字符.我可以在不使用for循环的情况下做到这一点吗(我可能错了,但是如果认为这样会更慢)?

but it only takes the characters one by one. Can i do it without using a for loop (I might be wrong but if think it would be slower) ?

推荐答案

您可以对长度为2的子字符串进行 range(..):

You could range(..) over substrings of length 2:

c = '8db6796fee32785e366f710df10cc' 
c2=[int(c[i:i+2],16) for i in range(0,len(c),2)]

因此, i 以2的步长对字符串进行迭代,然后从 i i + 2 (不包括)获取长度为2的子字符串)和 c [i:i + 2] .您可以通过采用 int(..,16).

So i iterates of the string with steps of 2 and you take a substring of length 2 from i to i+2 (exclusive) with c[i:i+2]. These you convert by taking int(..,16).

对于您的示例输入,它将生成:

For your sample input it generates:

>>> c='8db6796fee32785e366f710df10cc'
>>> [int(c[i:i+2],16) for i in range(0,len(c),2)]
[141, 182, 121, 111, 238, 50, 120, 94, 54, 111, 113, 13, 241, 12, 12]

最后一个元素是 12 ,因为字符串的长度是奇数,所以它将 c 作为要解析的最后一个元素.

The last element is 12 because the length of your string is odd, so it takes c as the last element to parse.

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

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