简体   繁体   English

Python 3二进制到十六进制带填充

[英]Python 3 binary to hexadecimal with padding

In Python 3 how would I turn binary into a hexadecimal with padding for example "00001111" would equal "0F" i would like it to include a 0 with no 0x attached aswell. 在Python 3中,如何将带有填充的二进制文件转换为十六进制,例如“ 00001111”将等于“ 0F”,我希望它也包含一个不带0x的0。 I use this to convert binary to hexadecimal: 我用它来将二进制转换为十六进制:

def bin2hex(binary):
return ''.join((hex(int(binary[i:i+8], 2))[2:] for i in range(0, len(binary), 8)))

print(bin2hex("00001111")) 打印(BIN2HEX( “00001111”))

Result: "F" 结果:“ F”

But it does not include a 0. 但它不包含0。

You made a mistake: a hexadecimal character is equivalent to four bits, not eight: 您犯了一个错误:十六进制字符等于四位 ,而不是八位:

def bin2hex(binary):
    return ''.join(hex(int(binary[i:i+4], 2))[2:] for i in range(0, len(binary), 4))

That being said, I think you make things too complicated, you can simply use Python's string formatting: 话虽这么说,我认为您使事情变得太复杂了,您可以简单地使用Python的字符串格式:

def bin2hex(binary):
    return '{:02x}'.format(int(binary, 2))

Or for an arbitrary number of bits (dividable by 4): 或对于任意数量的位(可除以4):

def bin2hex(binary):
    return '{:0{}x}'.format(int(binary, 2), len(binary)//4)

of for a number of bits that is not per se dividable by 4: 的一个比特数是不本身可分割由4:

def bin2hex(binary):
    return '{:0{}x}'.format(int(binary, 2), (len(binary)+3)//4)

or with string interpolation , like @HåkenLid said: 或使用字符串插值 ,例如@HåkenLid说:

def bin2hex(binary):
    return f'{int(binary, 2):0{(len(binary)+3)//4}x}'

For example: 例如:

>>> bin2hex('0001')
'1'
>>> bin2hex('00011100')
'1c'
>>> bin2hex('000111001011')
'1cb'
>>> bin2hex('1101000111001011')
'd1cb'

One simple way to do that would be to use the zfill string method. 一种简单的方法是使用zfill字符串方法。

def bin2hex(binary):
    return hex(int(binary, 2))[2:].zfill(len(binary)//4)

bin2hex('00001111')
# >>> 0f

bin2hex('000000001111')
# >>> 00f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM