将整数转换为特定格式的十六进制字符串 [英] Convert integer to hex-string with specific format

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

问题描述

我是python的新手,并且存在以下问题:我需要将整数转换为6字节的十六进制字符串。



例如。
281473900746245 - >\xFF\xFF\xBF\xDE\x16\x05



十六进制字符串的格式很重要。 int值的长度是可变的。



格式'0xffffbf949309L'不适用于我。 (我使用十六进制(int-value)得到它)






我的最终解决方案一些玩)是:

$ $ p $ code def def_tohex(self,int_value):
data_ = format(int_value,' x')

结果= data_.rjust(12,'0')
hexed = unhexlify(结果)

返回格式

感谢您的所有帮助!

解决方案
$ p
$ b

  x = 281473900746245 
decode_x = hex(x)[2:]。decode('hex')#value:'\xff\xff\xbf\xde\x16\x05'

细分:

  hex(x)#value: '0xffffbfde1605'
hex(x)[2:]#value:'ffffbfde1605'
hex(x)[2:]。decode('hex')#value:'\xff\xff \xbf\xde\x16\x05'

更新:



Per @ multipleinstances和@ Sven的评论,因为您可能正在处理较长的值,您可能需要调整输出十六进制:

  format(x,'x')#value:'ffffbfde1605'
code>

但是,有时候,十六进制的输出可能是奇数长度,这会破坏解码,所以它可能会更好创建一个函数来执行此操作:

$ pre $ def $(int_value)
encoded = format(int_value,'x ')

长度= len(编码)
编码= encoded.zfill(长度+长度%2)

返回encoded.decode('hex')


I am new to python and have following problem: I need to convert an integer to a hex string with 6 bytes.

e.g. 281473900746245 --> "\xFF\xFF\xBF\xDE\x16\x05"

The format of the hex-string is important. The length of the int value is variable.

The format '0xffffbf949309L' don't work for me. (I get this with hex(int-value))


My final solution (after some "playing") is:

def _tohex(self, int_value):
    data_ = format(int_value, 'x')

    result = data_.rjust(12, '0')
    hexed = unhexlify(result)

    return hexed

Thank you for all the help!

解决方案

There might be a better solution, but you can do this:

x = 281473900746245
decoded_x = hex(x)[2:].decode('hex') # value: '\xff\xff\xbf\xde\x16\x05'

Breakdown:

hex(x)                     # value: '0xffffbfde1605'
hex(x)[2:]                 # value: 'ffffbfde1605'
hex(x)[2:].decode('hex')   # value: '\xff\xff\xbf\xde\x16\x05'

Update:

Per @multipleinstances and @Sven's comments, since you might be dealing with long values, you might have to tweak the output of hex a little bit:

format(x, 'x')     # value: 'ffffbfde1605'

Sometimes, however, the output of hex might be an odd-length, which would break decode, so it'd probably be better to create a function to do this:

def convert(int_value):
   encoded = format(int_value, 'x')

   length = len(encoded)
   encoded = encoded.zfill(length+length%2)

   return encoded.decode('hex')

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

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