Oxy*_*ron 9 python string int hex
我是python的新手,有以下问题:我需要将一个整数转换为一个6字节的十六进制字符串.
例如281473900746245 - >"\ xFF\xFF\xBF\xDE\x16\x05"
十六进制字符串的格式很重要.int值的长度是可变的.
格式'0xffffbf949309L'对我不起作用.(我用hex(int-value)得到这个)
我的最终解决方案(在一些"播放"之后)是:
def _tohex(self, int_value):
data_ = format(int_value, 'x')
result = data_.rjust(12, '0')
hexed = unhexlify(result)
return hexed
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
Man*_*y D 13
可能有更好的解决方案,但您可以这样做:
x = 281473900746245
decoded_x = hex(x)[2:].decode('hex') # value: '\xff\xff\xbf\xde\x16\x05'
Run Code Online (Sandbox Code Playgroud)
分解:
hex(x) # value: '0xffffbfde1605'
hex(x)[2:] # value: 'ffffbfde1605'
hex(x)[2:].decode('hex') # value: '\xff\xff\xbf\xde\x16\x05'
Run Code Online (Sandbox Code Playgroud)
更新:
根据@multipleinstances和@Sven的注释,因为你可能正在处理long值,你可能需要稍微调整一下hex的输出:
format(x, 'x') # value: 'ffffbfde1605'
Run Code Online (Sandbox Code Playgroud)
但是,有时候,hex的输出可能是奇数长度,这会破坏解码,因此创建一个函数可能更好:
def convert(int_value):
encoded = format(int_value, 'x')
length = len(encoded)
encoded = encoded.zfill(length+length%2)
return encoded.decode('hex')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36489 次 |
| 最近记录: |