138

我有 ABC123EFFF。

我想要 001010101111000001001000111110111111111111 (即二进制表示,例如,42 位数字和前导零)。

如何?

4

22 回答 22

137

为了解决左侧尾随零问题:


my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)

它将给出 00011010 而不是修剪后的版本。

于 2011-02-01T07:17:53.273 回答
72
import binascii

binary_string = binascii.unhexlify(hex_string)

binascii.unhexlify

返回由指定为参数的十六进制字符串表示的二进制数据。

于 2009-09-15T06:45:15.627 回答
61

将十六进制转换为二进制

我有 ABC123EFFF。

我想要 001010101111000001001000111110111111111111 (即二进制表示,例如,42 位数字和前导零)。

简短的回答:

Python 3.6 中的新 f 字符串允许您使用非常简洁的语法来执行此操作:

>>> f'{0xABC123EFFF:0>42b}'
'001010101111000001001000111110111111111111'

或者用语义打破它:

>>> number, pad, rjust, size, kind = 0xABC123EFFF, '0', '>', 42, 'b'
>>> f'{number:{pad}{rjust}{size}{kind}}'
'001010101111000001001000111110111111111111'

长答案:

你实际上是说你有一个十六进制表示的值,你想用二进制表示一个等效值。

equivalence 的值是一个整数。但是您可以以字符串开头,并且要以二进制形式查看,您必须以字符串结尾。

将十六进制转换为二进制、42 位数字和前导零?

我们有几种直接的方法来实现这个目标,而无需使用切片。

首先,在我们进行任何二进制操作之前,先转换为 int(我认为这是字符串格式,而不是文字):

>>> integer = int('ABC123EFFF', 16)
>>> integer
737679765503

或者,我们可以使用以十六进制形式表示的整数文字:

>>> integer = 0xABC123EFFF
>>> integer
737679765503

现在我们需要用二进制表示来表示我们的整数。

使用内置函数,format

然后传递给format

>>> format(integer, '0>42b')
'001010101111000001001000111110111111111111'

这使用了格式化规范的mini-language

为了打破它,这是它的语法形式:

[[fill]align][sign][#][0][width][,][.precision][type]

为了使其成为满足我们需求的规范,我们只是排除了我们不需要的东西:

>>> spec = '{fill}{align}{width}{type}'.format(fill='0', align='>', width=42, type='b')
>>> spec
'0>42b'

并将其传递给格式

>>> bin_representation = format(integer, spec)
>>> bin_representation
'001010101111000001001000111110111111111111'
>>> print(bin_representation)
001010101111000001001000111110111111111111

字符串格式化(模板)与str.format

我们可以在字符串 usingstr.format方法中使用它:

>>> 'here is the binary form: {0:{spec}}'.format(integer, spec=spec)
'here is the binary form: 001010101111000001001000111110111111111111'

或者只是将规范直接放在原始字符串中:

>>> 'here is the binary form: {0:0>42b}'.format(integer)
'here is the binary form: 001010101111000001001000111110111111111111'

使用新的 f 字符串进行字符串格式化

让我们演示一下新的 f 弦。它们使用相同的迷你语言格式规则:

>>> integer = 0xABC123EFFF
>>> length = 42
>>> f'{integer:0>{length}b}'
'001010101111000001001000111110111111111111'

现在让我们将此功能放入一个函数中以鼓励可重用性:

def bin_format(integer, length):
    return f'{integer:0>{length}b}'

现在:

>>> bin_format(0xABC123EFFF, 42)
'001010101111000001001000111110111111111111'    

在旁边

如果您实际上只是想将数据编码为内存或磁盘中的字节字符串,则可以使用该int.to_bytes方法,该方法仅在 Python 3 中可用:

>>> help(int.to_bytes)
to_bytes(...)
    int.to_bytes(length, byteorder, *, signed=False) -> bytes
...

由于 42 位除以每个字节 8 位等于 6 个字节:

>>> integer.to_bytes(6, 'big')
b'\x00\xab\xc1#\xef\xff'
于 2016-05-14T02:34:52.253 回答
59
bin(int("abc123efff", 16))[2:]
于 2009-09-15T06:59:24.257 回答
32
>>> bin( 0xABC123EFFF )

'0b1010101111000001001000111110111111111111'

于 2014-07-29T13:10:58.683 回答
18

使用内置的format() 函数int() 函数 简单易懂。这是亚伦答案的简化版

整数()

int(string, base)

格式()

format(integer, # of bits)

例子

# w/o 0b prefix
>> format(int("ABC123EFFF", 16), "040b")
1010101111000001001000111110111111111111

# with 0b prefix
>> format(int("ABC123EFFF", 16), "#042b")
0b1010101111000001001000111110111111111111

# w/o 0b prefix + 64bit
>> format(int("ABC123EFFF", 16), "064b")
0000000000000000000000001010101111000001001000111110111111111111

另请参阅此答案

于 2019-09-24T04:35:21.897 回答
14
"{0:020b}".format(int('ABC123EFFF', 16))
于 2012-02-28T17:28:51.000 回答
10

这是一种使用位摆弄来生成二进制字符串的相当原始的方法。

要理解的关键点是:

(n & (1 << i)) and 1

如果设置了 n 的第 i 位,它将生成 0 或 1。


import binascii

def byte_to_binary(n):
    return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8)))

def hex_to_binary(h):
    return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h))

print hex_to_binary('abc123efff')

>>> 1010101111000001001000111110111111111111

编辑:使用“新”三元运算符:

(n & (1 << i)) and 1

会成为:

1 if n & (1 << i) or 0

(我不确定哪个 TBH 的可读性)

于 2009-09-15T15:22:44.870 回答
5

这与 Glen Maynard 的解决方案略有不同,我认为这是正确的做法。它只是添加了填充元素。


    def hextobin(self, hexval):
        '''
        Takes a string representation of hex data with
        arbitrary length and converts to string representation
        of binary.  Includes padding 0s
        '''
        thelen = len(hexval)*4
        binval = bin(int(hexval, 16))[2:]
        while ((len(binval)) < thelen):
            binval = '0' + binval
        return binval

把它从课堂上拉了出来。self, 如果您正在使用独立脚本,请取出。

于 2011-09-10T17:44:44.093 回答
5

我将要填充的位数的计算添加到 Onedinkenedi 的解决方案中。这是结果函数:

def hextobin(h):
  return bin(int(h, 16))[2:].zfill(len(h) * 4)

其中 16 是您要转换的基数(十六进制),而 4 是表示每个数字所需的位数,或以 2 为基数的刻度。

于 2015-03-07T09:21:39.617 回答
3

用相应的 4 个二进制数字替换每个十六进制数字:

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111
于 2009-09-15T06:46:10.057 回答
2

十六进制->十进制然后十进制->二进制

#decimal to binary 
def d2b(n):
    bStr = ''
    if n < 0: raise ValueError, "must be a positive integer"
    if n == 0: return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1    
    return bStr

#hex to binary
def h2b(hex):
    return d2b(int(hex,16))
于 2009-10-05T11:00:55.213 回答
1

另一种方式:

import math

def hextobinary(hex_string):
    s = int(hex_string, 16) 
    num_digits = int(math.ceil(math.log(s) / math.log(2)))
    digit_lst = ['0'] * num_digits
    idx = num_digits
    while s > 0:
        idx -= 1
        if s % 2 == 1: digit_lst[idx] = '1'
        s = s / 2
    return ''.join(digit_lst)

print hextobinary('abc123efff')
于 2009-09-15T19:24:01.887 回答
1

ABC123EFFF的二进制版本实际上是1010101111000001001000111110111111111111

对于几乎所有应用程序,您希望二进制版本的长度是 4 的倍数,前导填充为 0。

要在 Python 中得到这个:

def hex_to_binary( hex_code ):
  bin_code = bin( hex_code )[2:]
  padding = (4-len(bin_code)%4)%4
  return '0'*padding + bin_code

示例 1:

>>> hex_to_binary( 0xABC123EFFF )
'1010101111000001001000111110111111111111'

示例 2:

>>> hex_to_binary( 0x7123 )
'0111000100100011'

请注意,这也适用于 Micropython :)

于 2019-10-08T16:08:22.910 回答
1

只需使用模块coden (注意:我是模块的作者)

您可以在那里将十六进制转换为二进制。

  1. 使用pip安装
pip install coden
  1. 兑换
a_hexadecimal_number = "f1ff"
binary_output = coden.hex_to_bin(a_hexadecimal_number)

转换关键字是:

  • hex表示十六进制
  • 二进制的bin
  • int表示十进制
  • _to_ - 函数的转换关键字

所以你也可以格式化:e。hexadecimal_output = bin_to_hex(a_binary_number)

于 2020-06-22T13:24:49.143 回答
1
# Python Program - Convert Hexadecimal to Binary
hexdec = input("Enter Hexadecimal string: ")
print(hexdec," in Binary = ", end="")    # end is by default "\n" which prints a new line
for _hex in hexdec:
    dec = int(_hex, 16)    # 16 means base-16 wich is hexadecimal
    print(bin(dec)[2:].rjust(4,"0"), end="")    # the [2:] skips 0b, and the 
于 2019-09-20T17:23:46.790 回答
0

我有一个简短的希望可以帮助:-)

input = 'ABC123EFFF'
for index, value in enumerate(input):
    print(value)
    print(bin(int(value,16)+16)[3:])

string = ''.join([bin(int(x,16)+16)[3:] for y,x in enumerate(input)])
print(string)

首先,我使用您的输入并枚举它以获取每个符号。然后我将其转换为二进制并从第 3 个位置修剪到末尾。获得 0 的技巧是添加输入的最大值 -> 在这种情况下总是 16 :-)

简短的形式是连接方法。享受。

于 2016-04-27T08:31:51.383 回答
0
 def conversion():
    e=raw_input("enter hexadecimal no.:")
    e1=("a","b","c","d","e","f")
    e2=(10,11,12,13,14,15)
    e3=1
    e4=len(e)
    e5=()
    while e3<=e4:
        e5=e5+(e[e3-1],)
        e3=e3+1
    print e5
    e6=1
    e8=()
    while e6<=e4:
        e7=e5[e6-1]
        if e7=="A":
            e7=10
        if e7=="B":
            e7=11
        if e7=="C":
            e7=12
        if e7=="D":
            e7=13
        if e7=="E":
            e7=14
        if e7=="F":
            e7=15
        else:
            e7=int(e7)
        e8=e8+(e7,)
        e6=e6+1
    print e8

    e9=1
    e10=len(e8)
    e11=()
    while e9<=e10:
        e12=e8[e9-1]
        a1=e12
        a2=()
        a3=1 
        while a3<=1:
            a4=a1%2
            a2=a2+(a4,)
            a1=a1/2
            if a1<2:
                if a1==1:
                    a2=a2+(1,)
                if a1==0:
                    a2=a2+(0,)
                a3=a3+1
        a5=len(a2)
        a6=1
        a7=""
        a56=a5
        while a6<=a5:
            a7=a7+str(a2[a56-1])
            a6=a6+1
            a56=a56-1
        if a5<=3:
            if a5==1:
                a8="000"
                a7=a8+a7
            if a5==2:
                a8="00"
                a7=a8+a7
            if a5==3:
                a8="0"
                a7=a8+a7
        else:
            a7=a7
        print a7,
        e9=e9+1
于 2016-01-03T07:42:54.890 回答
-1
a = raw_input('hex number\n')
length = len(a)
ab = bin(int(a, 16))[2:]
while len(ab)<(length * 4):
    ab = '0' + ab
print ab
于 2015-02-09T10:09:57.467 回答
-1
import binascii
hexa_input = input('Enter hex String to convert to Binary: ')
pad_bits=len(hexa_input)*4
Integer_output=int(hexa_input,16)
Binary_output= bin(Integer_output)[2:]. zfill(pad_bits)
print(Binary_output)
"""zfill(x) i.e. x no of 0 s to be padded left - Integers will overwrite 0 s
starting from right side but remaining 0 s will display till quantity x
[y:] where y is no of output chars which need to destroy starting from left"""
于 2015-10-02T21:48:08.737 回答
-1
HEX_TO_BINARY_CONVERSION_TABLE = {
                              '0': '0000',

                              '1': '0001',

                              '2': '0010',

                              '3': '0011',

                              '4': '0100',

                              '5': '0101',

                              '6': '0110',

                              '7': '0111',

                              '8': '1000',

                              '9': '1001',

                              'a': '1010',

                              'b': '1011',

                              'c': '1100',

                              'd': '1101',

                              'e': '1110',

                              'f': '1111'}

def hex_to_binary(hex_string):
    binary_string = ""
    for character in hex_string:
        binary_string += HEX_TO_BINARY_CONVERSION_TABLE[character]
    return binary_string

当我计时hex_to_binary("123ade")

  %timeit hex_to_binary("123ade")

结果如下:

 316 ns ± 2.52 ns per loop

或者,您可以使用“加入”方法:

def hex_to_binary_join(hex_string):
    hex_array=[]
    for character in hex_string:
        hex_array.append(HEX_TO_BINARY_CONVERSION_TABLE[character])
    return "".join(hex_array)

我也计时了:

    %timeit hex_to_binary_join("123ade")
       397 ns ± 4.64 ns per loop 
于 2020-08-11T01:48:17.993 回答
-7
no=raw_input("Enter your number in hexa decimal :")
def convert(a):
    if a=="0":
        c="0000"
    elif a=="1":
        c="0001"
    elif a=="2":
        c="0010"
    elif a=="3":
        c="0011"
    elif a=="4":
        c="0100"
    elif a=="5":
        c="0101"
    elif a=="6":
        c="0110"
    elif a=="7":
        c="0111"
    elif a=="8":
        c="1000"
    elif a=="9":
        c="1001"
    elif a=="A":
        c="1010"
    elif a=="B":
        c="1011"
    elif a=="C":
        c="1100"
    elif a=="D":
        c="1101"
    elif a=="E":
        c="1110"
    elif a=="F":
        c="1111"
    else:
        c="invalid"
    return c

a=len(no)
b=0
l=""
while b<a:
    l=l+convert(no[b])
    b+=1
print l
于 2012-03-13T15:21:11.620 回答