Python中的十六进制编码十进制

时间:2016-01-12 21:46:28

标签: python hex

我需要创建一个接受整数的函数,并返回一个编码为Hex Coded Decimal的整数的二进制字符串,以便以后打包成结构。

例如,我写了这个:

def convert_int(x):
    """
    Accepts an integer, outputs a hexadecimal string in HCD format
    Caution! Byte order is ALREADY little endian!
    """
    result = b''
    while x > 0:
        hcd = chr(int(str(divmod(x, 100)[1]), 16))
        result = result + hcd
        x = divmod(x, 100)[0]
    return result

因此convert_int(1234)将为3412h,依此类推。写这篇文章的Pythonic和优雅方式是什么?

upd:使函数输出小端字符串准备打包。

5 个答案:

答案 0 :(得分:1)

def convert_to_hcd(num):
    chars = []
    while num:
        num, ones = divmod(num, 10)
        num, tens = divmod(num, 10)
        chars.append(chr(tens * 16 + ones))
    chars.reverse()
    return "".join(chars)

convert_to_hcd(1234)    # => returns '\x124' (which is correct because '\x34' == '4')

答案 1 :(得分:0)

所以,对我来说正确的代码如下,请注意字节顺序是反转的(小端)

def convert_int(x):
"""
Accepts an integer, outputs a hexadecimal string in HCD format
Caution! Byte order is ALREADY little endian!
"""
result = b''
while x > 0:
    hcd = chr(int(str(divmod(x, 100)[1]), 16))
    result = result + hcd
    x = divmod(x, 100)[0]
return result

答案 2 :(得分:-1)

def intToHex(num):
    numBin = [int(n) for n in str(num)]
    result = 0
    for n in numBin:
        result = result*16 + n
    return(hex(result))

这很干净

答案 3 :(得分:-1)

这个小片段怎么样......:)

def convert_to_hcd(num): return "".join([ "\\x"+ (lambda i, k: ""+i+k if i !='m' else "0"+k)(i,k) for i,k in zip(( {NUM {1}} {NUM {1}} {NUM {1}} {NUM {1}} {NUM {1}} {NUM {1}}

答案 4 :(得分:-3)

>>> hex(1234)
'0x4d2'

谷歌不是你的敌人......