标签归档:hex

将十六进制转换为二进制

问题:将十六进制转换为二进制

我有ABC123EFFF。

我想拥有00101010111100000100001111110111111111111111(例如,二进制表示,具有42位数字和前导零)。

怎么样?

I have ABC123EFFF.

I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).

How?


回答 0

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


my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

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

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

For solving the left-side trailing zero problem:


my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

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

It will give 00011010 instead of the trimmed version.


回答 1

import binascii

binary_string = binascii.unhexlify(hex_string)

双歧杆菌

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

import binascii

binary_string = binascii.unhexlify(hex_string)

Read

binascii.unhexlify

Return the binary data represented by the hexadecimal string specified as the parameter.


回答 2

bin(int("abc123efff", 16))[2:]
bin(int("abc123efff", 16))[2:]

回答 3

将十六进制转换为二进制

我有ABC123EFFF。

我想拥有001010101111000001001000111110111111111111111(即具有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'

长答案:

您实际上要说的是,您有一个以十六进制表示形式的值,并且您想要以二进制形式表示一个等效值。

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

将十六进制转换为二进制,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

我们可以在使用str.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'

Convert hex to binary

I have ABC123EFFF.

I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).

Short answer:

The new f-strings in Python 3.6 allow you to do this using very terse syntax:

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

or to break that up with the semantics:

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

Long answer:

What you are actually saying is that you have a value in a hexadecimal representation, and you want to represent an equivalent value in binary.

The value of equivalence is an integer. But you may begin with a string, and to view in binary, you must end with a string.

Convert hex to binary, 42 digits and leading zeros?

We have several direct ways to accomplish this goal, without hacks using slices.

First, before we can do any binary manipulation at all, convert to int (I presume this is in a string format, not as a literal):

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

alternatively we could use an integer literal as expressed in hexadecimal form:

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

Now we need to express our integer in a binary representation.

Use the builtin function, format

Then pass to format:

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

This uses the formatting specification’s mini-language.

To break that down, here’s the grammar form of it:

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

To make that into a specification for our needs, we just exclude the things we don’t need:

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

and just pass that to format

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

String Formatting (Templating) with str.format

We can use that in a string using str.format method:

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

Or just put the spec directly in the original string:

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

String Formatting with the new f-strings

Let’s demonstrate the new f-strings. They use the same mini-language formatting rules:

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

Now let’s put this functionality into a function to encourage reusability:

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

And now:

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

Aside

If you actually just wanted to encode the data as a string of bytes in memory or on disk, you can use the int.to_bytes method, which is only available in Python 3:

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

And since 42 bits divided by 8 bits per byte equals 6 bytes:

>>> integer.to_bytes(6, 'big')
b'\x00\xab\xc1#\xef\xff'

回答 4

>>> bin( 0xABC123EFFF )

‘0b1010101111000000000010001000111110111111111111’

>>> bin( 0xABC123EFFF )

‘0b1010101111000001001000111110111111111111’


回答 5

"{0:020b}".format(int('ABC123EFFF', 16))
"{0:020b}".format(int('ABC123EFFF', 16))

回答 6

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

要了解的关键是:

(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的可读性)

Here’s a fairly raw way to do it using bit fiddling to generate the binary strings.

The key bit to understand is:

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

Which will generate either a 0 or 1 if the i’th bit of n is set.


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

Edit: using the “new” ternary operator this:

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

Would become:

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

(Which TBH I’m not sure how readable that is)


回答 7

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


    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, 如果您使用的是独立脚本,则只需取出。

This is a slight touch up to Glen Maynard’s solution, which I think is the right way to do it. It just adds the padding element.


    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)) &lt thelen):
            binval = '0' + binval
        return binval

Pulled it out of a class. Just take out self, if you’re working in a stand-alone script.


回答 8

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

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

另请参阅此答案

Use Built-in format() function and int() function It’s simple and easy to understand. It’s little bit simplified version of Aaron answer

int()

int(string, base)

format()

format(integer, # of bits)

Example

# 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

See also this answer


回答 9

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

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111

Replace each hex digit with the corresponding 4 binary digits:

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111

回答 10

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

#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))

hex –> decimal then decimal –> binary

#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))

回答 11

其他方式:

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')

Another way:

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')

回答 12

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

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

其中16是您要转换的基数(十六进制),4是表示每个数字需要多少位,或者以小数位对数2为底。

I added the calculation for the number of bits to fill to Onedinkenedi’s solution. Here is the resulting function:

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

Where 16 is the base you’re converting from (hexadecimal), and 4 is how many bits you need to represent each digit, or log base 2 of the scale.


回答 13

 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
 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

回答 14

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

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 :-)

缩写形式为join方法。请享用。

i have a short snipped hope that helps :-)

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)

first i use your input and enumerate it to get each symbol. then i convert it to binary and trim from 3th position to the end. The trick to get the 0 is to add the max value of the input -> in this case always 16 :-)

the short form ist the join method. Enjoy.


回答 15

# 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 
# 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 

回答 16

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

对于几乎所有应用程序,您都希望二进制版本的长度为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 :)

The binary version of ABC123EFFF is actually 1010101111000001001000111110111111111111

For almost all applications you want the binary version to have a length that is a multiple of 4 with leading padding of 0s.

To get this in 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

Example 1:

>>> hex_to_binary( 0xABC123EFFF )
'1010101111000001001000111110111111111111'

Example 2:

>>> hex_to_binary( 0x7123 )
'0111000100100011'

Note that this also works in Micropython :)


回答 17

只需使用模块编码即可 (注意:我是该模块的作者)

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

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

转换关键字为:

  • 十六进制的hexadeimal
  • 二进制
  • INT十进制
  • _to_-函数的转换关键字

因此,您还可以格式化:e。十六进制输出= bin_to_hex(a_binary_number)

Just use the module coden (note: I am the author of the module)

You can convert haxedecimal to binary there.

  1. Install using pip
pip install coden
  1. Convert
a_hexadecimal_number = "f1ff"
binary_output = coden.hex_to_bin(a_hexadecimal_number)

The converting Keywords are:

  • hex for hexadeimal
  • bin for binary
  • int for decimal
  • _to_ – the converting keyword for the function

So you can also format: e. hexadecimal_output = bin_to_hex(a_binary_number)


回答 18

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_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

回答 19

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
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

回答 20

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"""
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"""

回答 21

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
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

将字符串打印为十六进制字节?

问题:将字符串打印为十六进制字节?

我有这个字符串:Hello world !!我想使用Python作为打印它48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21

hex() 仅适用于整数。

如何做呢?

I have this string: Hello world !! and I want to print it using Python as 48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21.

hex() works only for integers.

How can it be done?


回答 0

您可以将字符串转换为int生成器,对每个元素应用十六进制格式,并使用分隔符插入:

>>> s = "Hello world !!"
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21

Your can transform your string to a int generator, apply hex formatting for each element and intercalate with separator:

>>> s = "Hello world !!"
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21

回答 1

':'.join(x.encode('hex') for x in 'Hello World!')
':'.join(x.encode('hex') for x in 'Hello World!')

回答 2

对于Python 2.x:

':'.join(x.encode('hex') for x in 'Hello World!')

上面的代码不适用于Python 3.x,对于3.x,下面的代码将起作用:

':'.join(hex(ord(x))[2:] for x in 'Hello World!')

For Python 2.x:

':'.join(x.encode('hex') for x in 'Hello World!')

The code above will not work with Python 3.x, for 3.x, the code below will work:

':'.join(hex(ord(x))[2:] for x in 'Hello World!')

回答 3

两行中的另一个答案可能使某些人更容易阅读,并且有助于调试字符串中的换行符或其他奇数字符:

对于Python 2.7

for character in string:
    print character, character.encode('hex')

对于Python 3.7(未在3的所有版本上进行测试)

for character in string:
    print(character, character.encode('utf-8').hex())

Another answer in two lines that some might find easier to read, and helps with debugging line breaks or other odd characters in a string:

For Python 2.7

for character in string:
    print character, character.encode('hex')

For Python 3.7 (not tested on all releases of 3)

for character in string:
    print(character, character.encode('utf-8').hex())

回答 4

Fedor Gogolev答案的一些补充:

首先,如果字符串包含“ ASCII码”低于10的字符,则不会按要求显示它们。在这种情况下,正确的格式应为{:02x}

>>> s = "Hello unicode \u0005 !!"
>>> ":".join("{0:x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:5:20:21:21'
                                           ^

>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:05:20:21:21'
                                           ^^

其次,如果您的“字符串”实际上是“字节字符串”-并且由于区别在Python 3中很重要-您可能更喜欢以下内容:

>>> s = b"Hello bytes \x05 !!"
>>> ":".join("{:02x}".format(c) for c in s)
'48:65:6c:6c:6f:20:62:79:74:65:73:20:05:20:21:21'

请注意,由于字节对象被定义“范围在0 <= x <256之间的不可变整数序列”,因此不需要在上面的代码中进行转换。

Some complements to Fedor Gogolev answer:

First, if the string contains characters whose ‘ASCII code’ is below 10, they will not be displayed as required. In that case, the correct format should be {:02x}:

>>> s = "Hello unicode \u0005 !!"
>>> ":".join("{0:x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:5:20:21:21'
                                           ^

>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:05:20:21:21'
                                           ^^

Second, if your “string” is in reality a “byte string” — and since the difference matters in Python 3 — you might prefer the following:

>>> s = b"Hello bytes \x05 !!"
>>> ":".join("{:02x}".format(c) for c in s)
'48:65:6c:6c:6f:20:62:79:74:65:73:20:05:20:21:21'

Please note there is no need for conversion in the above code as a bytes objects is defined as “an immutable sequence of integers in the range 0 <= x < 256”.


回答 5

将字符串打印为十六进制字节?

接受的答案给出:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

返回:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

只要您使用字节(主要是ascii字符),可接受的答案就起作用。但是,如果您使用unicode,例如:

a_string = u"Привет мир!!" # "Prevyet mir", or "Hello World" in Russian.

您需要以某种方式转换为字节。

如果您的终端不接受这些字符,则可以从UTF-8解码或使用名称(以便可以与我一起粘贴并运行代码):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

因此,我们看到:

":".join("{:02x}".format(ord(c)) for c in a_string)

退货

'41f:440:438:432:435:442:20:43c:438:440:21:21'

不良/意外的结果-这些代码点结合在一起,构成了来自Unicode联盟的Unicode 字形,代表了全世界的语言。但是,这并不是我们实际存储此信息的方式,因此可以由其他来源对其进行解释。

为了允许另一个源使用此数据,我们通常需要转换为UTF-8编码,例如,将该字符串以字节为单位保存到磁盘或发布为html。因此,我们需要进行编码以将代码点转换为UTF-8 的代码单元 -在Python 3中ord是不需要的,因为bytes整数是可迭代的:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

或者,也许更优雅地使用新的f字符串(仅在Python 3中可用):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

在Python 2中,请c转到ord第一个,即ord(c)-更多示例:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Print a string as hex bytes?

The accepted answer gives:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

returns:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:

a_string = u"Привет мир!!" # "Prevyet mir", or "Hello World" in Russian.

You need to convert to bytes somehow.

If your terminal doesn’t accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

So we see that:

":".join("{:02x}".format(ord(c)) for c in a_string)

returns

'41f:440:438:432:435:442:20:43c:438:440:21:21'

a poor/unexpected result – these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium – representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.

To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 – in Python 3, ord is not needed because bytes are iterables of integers:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Or perhaps more elegantly, using the new f-strings (only available in Python 3):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

In Python 2, pass c to ord first, i.e. ord(c) – more examples:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

回答 6

您可以使用hexdump

import hexdump
hexdump.dump("Hello World", sep=":")

.lower()如果需要小写,请附加)。这适用于Python 2和3。

You can use hexdump‘s

import hexdump
hexdump.dump("Hello World", sep=":")

(append .lower() if you require lower-case). This works for both Python 2 & 3.


回答 7

使用map和lambda函数可以生成一个十六进制值列表,可以将其打印(或用于其他目的)

>>> s = 'Hello 1 2 3 \x01\x02\x03 :)'

>>> map(lambda c: hex(ord(c)), s)
['0x48', '0x65', '0x6c', '0x6c', '0x6f', '0x20', '0x31', '0x20', '0x32', '0x20', '0x33', '0x20', '0x1', '0x2', '0x3', '0x20', '0x3a', '0x29']

Using map and lambda function can produce a list of hex values, which can be printed (or used for other purposes)

>>> s = 'Hello 1 2 3 \x01\x02\x03 :)'

>>> map(lambda c: hex(ord(c)), s)
['0x48', '0x65', '0x6c', '0x6c', '0x6f', '0x20', '0x31', '0x20', '0x32', '0x20', '0x33', '0x20', '0x1', '0x2', '0x3', '0x20', '0x3a', '0x29']

回答 8

这可以通过以下方式完成:

from __future__ import print_function
str = "Hello World !!"
for char in str:
    mm = int(char.encode('hex'), 16)
    print(hex(mm), sep=':', end=' ' )

此输出将为十六进制,如下所示:

0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64 0x20 0x21 0x21

This can be done in following ways:

from __future__ import print_function
str = "Hello World !!"
for char in str:
    mm = int(char.encode('hex'), 16)
    print(hex(mm), sep=':', end=' ' )

The output of this will be in hex as follows:

0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64 0x20 0x21 0x21


回答 9

对于那些不关心Python3或冒号的人来说,更通用一些:

from codecs import encode

data = open('/dev/urandom', 'rb').read(20)
print(encode(data, 'hex'))      # data

print(encode(b"hello", 'hex'))  # string

A bit more general for those who don’t care about Python3 or colons:

from codecs import encode

data = open('/dev/urandom', 'rb').read(20)
print(encode(data, 'hex'))      # data

print(encode(b"hello", 'hex'))  # string

回答 10

base64.b16encodepython2中使用(内置)

>>> s = 'Hello world !!'
>>> h = base64.b16encode(s)
>>> ':'.join([h[i:i+2] for i in xrange(0, len(h), 2)]
'48:65:6C:6C:6F:20:77:6F:72:6C:64:20:21:21'

Using base64.b16encode in python2 (its built-in)

>>> s = 'Hello world !!'
>>> h = base64.b16encode(s)
>>> ':'.join([h[i:i+2] for i in xrange(0, len(h), 2)]
'48:65:6C:6C:6F:20:77:6F:72:6C:64:20:21:21'

回答 11

为了方便起见,非常简单。

def hexlify_byteString(byteString, delim="%"):
    ''' very simple way to hexlify a bytestring using delimiters '''
    retval = ""
    for intval in byteString:
        retval += ( '0123456789ABCDEF'[int(intval / 16)])
        retval += ( '0123456789ABCDEF'[int(intval % 16)])
        retval += delim
    return( retval[:-1])

hexlify_byteString(b'Hello World!', ":")
# Out[439]: '48:65:6C:6C:6F:20:57:6F:72:6C:64:21'

Just for convenience, very simple.

def hexlify_byteString(byteString, delim="%"):
    ''' very simple way to hexlify a bytestring using delimiters '''
    retval = ""
    for intval in byteString:
        retval += ( '0123456789ABCDEF'[int(intval / 16)])
        retval += ( '0123456789ABCDEF'[int(intval % 16)])
        retval += delim
    return( retval[:-1])

hexlify_byteString(b'Hello World!', ":")
# Out[439]: '48:65:6C:6C:6F:20:57:6F:72:6C:64:21'

回答 12

对于性能比更高的东西''.format(),您可以使用以下代码:

>>> ':'.join( '%02x'%(v if type(v) is int else ord(v)) for v in 'Hello World !!' )
'48:65:6C:6C:6F:20:77:6F:72:6C:64:20:21:21'
>>> 
>>> ':'.join( '%02x'%(v if type(v) is int else ord(v)) for v in b'Hello World !!' )
'48:65:6C:6C:6F:20:77:6F:72:6C:64:20:21:21'
>>> 

抱歉,
如果一个人可以简单地做到'%02x'%v这一点,那就再好不过了,但这只需要int …,
但是您会被字节字符串所困扰,b''而没有选择逻辑ord(v)

for something that offers more performance than ''.format(), you can use this:

>>> ':'.join( '%02x'%(v if type(v) is int else ord(v)) for v in 'Hello World !!' )
'48:65:6C:6C:6F:20:77:6F:72:6C:64:20:21:21'
>>> 
>>> ':'.join( '%02x'%(v if type(v) is int else ord(v)) for v in b'Hello World !!' )
'48:65:6C:6C:6F:20:77:6F:72:6C:64:20:21:21'
>>> 

sorry this couldn’t look nicer
would be nice if one could simply do '%02x'%v, but that only takes int…
but you’ll be stuck with byte-strings b'' without the logic to select ord(v).


从十六进制编码的ASCII字符串转换为纯ASCII?

问题:从十六进制编码的ASCII字符串转换为纯ASCII?

如何在Python中将十六进制转换为纯ASCII?

请注意,例如,我要将“ 0x7061756c”转换为“ paul”。

How can I convert from hex to plain ASCII in Python?

Note that, for example, I want to convert “0x7061756c” to “paul”.


回答 0

一个稍微简单的解决方案:

>>> "7061756c".decode("hex")
'paul'

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

回答 1

无需导入任何库:

>>> bytearray.fromhex("7061756c").decode()
'paul'

No need to import any library:

>>> bytearray.fromhex("7061756c").decode()
'paul'

回答 2

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

我只是很开心,但重要的部分是:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

现在将看Binascii …

>>> print binascii.unhexlify('7061756c')
paul

很酷(而且我不知道为什么其他人想让您跳入困境,然后他们才会帮助您)。

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

i’m just having fun, but the important parts are:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

will look at binascii now…

>>> print binascii.unhexlify('7061756c')
paul

cool (and i have no idea why other people want to make you jump through hoops before they’ll help).


回答 3

在Python 2中:

>>> "7061756c".decode("hex")
'paul'

在Python 3中:

>>> bytes.fromhex('7061756c').decode('utf-8')
'paul'

In Python 2:

>>> "7061756c".decode("hex")
'paul'

In Python 3:

>>> bytes.fromhex('7061756c').decode('utf-8')
'paul'

回答 4

这是使用十六进制整数而不是十六进制字符串时的解决方案:

def convert_hex_to_ascii(h):
    chars_in_reverse = []
    while h != 0x0:
        chars_in_reverse.append(chr(h & 0xFF))
        h = h >> 8

    chars_in_reverse.reverse()
    return ''.join(chars_in_reverse)

print convert_hex_to_ascii(0x7061756c)

Here’s my solution when working with hex integers and not hex strings:

def convert_hex_to_ascii(h):
    chars_in_reverse = []
    while h != 0x0:
        chars_in_reverse.append(chr(h & 0xFF))
        h = h >> 8

    chars_in_reverse.reverse()
    return ''.join(chars_in_reverse)

print convert_hex_to_ascii(0x7061756c)

回答 5

或者,您也可以执行此操作…

Python 2解释器

print "\x70 \x61 \x75 \x6c"

user@linux:~# python
Python 2.7.14+ (default, Mar 13 2018, 15:23:44) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> print "\x70 \x61 \x75 \x6c"
p a u l
>>> exit()
user@linux:~# 

要么

Python 2单行

python -c 'print "\x70 \x61 \x75 \x6c"'

user@linux:~# python -c 'print "\x70 \x61 \x75 \x6c"'
p a u l
user@linux:~# 

Python 3解释器

user@linux:~$ python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print("\x70 \x61 \x75 \x6c")
p a u l

>>> print("\x70\x61\x75\x6c")
paul

Python 3单行

python -c 'print("\x70 \x61 \x75 \x6c")'

user@linux:~$ python -c 'print("\x70 \x61 \x75 \x6c")'
p a u l

user@linux:~$ python -c 'print("\x70\x61\x75\x6c")'
paul

Alternatively, you can also do this …

Python 2 Interpreter

print "\x70 \x61 \x75 \x6c"

Example

user@linux:~# python
Python 2.7.14+ (default, Mar 13 2018, 15:23:44) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> print "\x70 \x61 \x75 \x6c"
p a u l
>>> exit()
user@linux:~# 

or

Python 2 One-Liner

python -c 'print "\x70 \x61 \x75 \x6c"'

Example

user@linux:~# python -c 'print "\x70 \x61 \x75 \x6c"'
p a u l
user@linux:~# 

Python 3 Interpreter

user@linux:~$ python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print("\x70 \x61 \x75 \x6c")
p a u l

>>> print("\x70\x61\x75\x6c")
paul

Python 3 One-Liner

python -c 'print("\x70 \x61 \x75 \x6c")'

Example

user@linux:~$ python -c 'print("\x70 \x61 \x75 \x6c")'
p a u l

user@linux:~$ python -c 'print("\x70\x61\x75\x6c")'
paul

回答 6

在Python 3.3.2中进行了测试有多种方法可以完成此操作,这是最短的方法之一,仅使用python提供的工具即可:

import base64
hex_data ='57696C6C20796F7520636F6E76657274207468697320484558205468696E6720696E746F20415343494920666F72206D653F2E202E202E202E506C656565656173652E2E2E212121'
ascii_string = str(base64.b16decode(hex_data))[2:-1]
print (ascii_string)

当然,如果您不想导入任何内容,则可以随时编写自己的代码。像这样非常基本的东西:

ascii_string = ''
x = 0
y = 2
l = len(hex_data)
while y <= l:
    ascii_string += chr(int(hex_data[x:y], 16))
    x += 2
    y += 2
print (ascii_string)

Tested in Python 3.3.2 There are many ways to accomplish this, here’s one of the shortest, using only python-provided stuff:

import base64
hex_data ='57696C6C20796F7520636F6E76657274207468697320484558205468696E6720696E746F20415343494920666F72206D653F2E202E202E202E506C656565656173652E2E2E212121'
ascii_string = str(base64.b16decode(hex_data))[2:-1]
print (ascii_string)

Of course, if you don’t want to import anything, you can always write your own code. Something very basic like this:

ascii_string = ''
x = 0
y = 2
l = len(hex_data)
while y <= l:
    ascii_string += chr(int(hex_data[x:y], 16))
    x += 2
    y += 2
print (ascii_string)

回答 7

b''.fromhex('7061756c')

不带分隔符使用

b''.fromhex('7061756c')

use it without delimiter


如何将int转换为十六进制字符串?

问题:如何将int转换为十六进制字符串?

我想将一个整数(将为<= 255)用于十六进制字符串表示形式

例如:我想通过65并离开'\x41',或255获得'\xff'

我曾尝试使用struct.pack('c',65来执行此操作),但9由于它想采用单个字符串,因此上述内容均会阻塞。

I want to take an integer (that will be <= 255), to a hex string representation

e.g.: I want to pass in 65 and get out '\x41', or 255 and get '\xff'.

I’ve tried doing this with the struct.pack('c',65), but that chokes on anything above 9 since it wants to take in a single character string.


回答 0

您正在寻找chr功能。

您似乎正在混合使用整数的十进制表示形式和整数的十六进制表示形式,因此尚不清楚您需要什么。根据您的描述,我认为这些片段之一可以显示您想要的内容。

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

请注意,这与包含整数(十六进制)的字符串完全不同。如果那是您想要的,请使用hex内置的。

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it’s not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.


回答 1

这会将整数转换为带有0x前缀的2位十六进制字符串:

strHex = "0x%0.2X" % 255

This will convert an integer to a 2 digit hex string with the 0x prefix:

strHex = "0x%0.2X" % 255

回答 2

hex()

hex(255)  # 0xff

如果您真的想\在前台就可以:

print '\\' + hex(255)[1:]

What about hex()?

hex(255)  # 0xff

If you really want to have \ in front you can do:

print '\\' + hex(255)[1:]

回答 3

尝试:

"0x%x" % 255 # => 0xff

要么

"0x%X" % 255 # => 0xFF

Python文档说:“把它放在枕头底下:http : //docs.python.org/library/index.html

Try:

"0x%x" % 255 # => 0xff

or

"0x%X" % 255 # => 0xFF

Python Documentation says: “keep this under Your pillow: http://docs.python.org/library/index.html


回答 4

让我添加这一点,因为有时您只想用一位数字表示:

'{:x}'.format(15)
> f

现在,使用新的f''格式字符串,您可以执行以下操作:

f'{15:x}'
> f

注意:最初的’f’ f'{15:x}'是表示格式字符串

Let me add this one, because sometimes you just want the single digit representation

( x can be lower, ‘x’, or uppercase, ‘X’, the choice determines if the output letters are upper or lower.):

'{:x}'.format(15)
> f

And now with the new f'' format strings you can do:

f'{15:x}'
> f

To add 0 padding you can use 0>n:

f'{2034:0>4X}'
> 07F2

NOTE: the initial ‘f’ in f'{15:x}' is to signify a format string


回答 5

如果要打包一个值小于255的结构(一个无符号字节,uint8_t)并以一个字符的字符串结尾,则可能要寻找格式B而不是c。C将字符转换为字符串(本身不太有用),而B将整数转换。

struct.pack('B', 65)

(是的,65是\ x41,而不是\ x65。)

struct类还将方便地处理通讯或其他用途的字节序。

If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you’re probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.

struct.pack('B', 65)

(And yes, 65 is \x41, not \x65.)

The struct class will also conveniently handle endianness for communication or other uses.


回答 6

请注意,对于较大的值,hex()仍然可以使用(某些其他答案无效):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2:0x4354467b746f6f5f736d616c6c3f7dL
Python 3:0x4354467b746f6f5f736d616c6c3f7d

对于解密的RSA消息,可以执行以下操作:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3

Note that for large values, hex() still works (some other answers don’t):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2: 0x4354467b746f6f5f736d616c6c3f7dL
Python 3: 0x4354467b746f6f5f736d616c6c3f7d

For a decrypted RSA message, one could do the following:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3

回答 7

这对我来说最好

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

如果您想要一个更大的宽度(2是2个十六进制打印字符),请更改(2),这样3将为您提供以下内容

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

回答 8

我希望将一个随机整数转换为以#开头的六位十六进制字符串。为了得到这个我用了

"#%6x" % random.randint(0xFFFFFF)

I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used

"#%6x" % random.randint(0xFFFFFF)

回答 9

随着format(),按照格式的例子,我们可以这样做:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

With format(), as per format-examples, we can do:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

回答 10

(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

例如:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'
(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()

For example:

>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'

回答 11

您也可以将任何基数的任何数字转换为十六进制。在这里使用这一行代码很容易使用:

hex(int(n,x)).replace("0x","")

您有一个字符串n,该字符串是您的数字以及x 该数字的基数。首先,将其更改为整数,然后更改为十六进制,但是十六进制首先更改为十六进制0x,因此replace我们将其删除。

Also you can convert any number in any base to hex. Use this one line code here it’s easy and simple to use:

hex(int(n,x)).replace("0x","")

You have a string n that is your number and x the base of that number. First, change it to integer and then to hex but hex has 0x at the first of it so with replace we remove it.


回答 12

作为替代表示,您可以使用

[in] '%s' % hex(15)
[out]'0xf'

As an alternative representation you could use

[in] '%s' % hex(15)
[out]'0xf'

在Python 3中将字节转换为十六进制字符串的正确方法是什么?

问题:在Python 3中将字节转换为十六进制字符串的正确方法是什么?

在Python 3中将字节转换为十六进制字符串的正确方法是什么?

我看到了bytes.hex方法,bytes.decode编解码器的声明,并尝试了其他最小惊讶的可能功能,但没有用。我只希望字节为十六进制!

What’s the correct way to convert bytes to a hex string in Python 3?

I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!


回答 0

从Python 3.5开始,这终于不再笨拙了:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

并反向:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

也适用于可变bytearray类型。

参考:https : //docs.python.org/3/library/stdtypes.html#bytes.hex

Since Python 3.5 this is finally no longer awkward:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex


回答 1

使用binascii模块:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

查看此答案: Python 3.1.1字符串转换为十六进制

Use the binascii module:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

See this answer: Python 3.1.1 string to hex


回答 2

Python具有逐个字节的标准编解码器,可以执行方便的转换,例如带引号的可打印(适合7位ascii),base64(适合字母数字),十六进制转义,gzip和bz2压缩。在Python 2中,您可以执行以下操作:

b'foo'.encode('hex')

在Python 3中,str.encode/ bytes.decode严格用于字节<-> str转换。相反,您可以执行此操作,该操作适用于Python 2和Python 3(反之为s / encode / decode / g):

import codecs
codecs.getencoder('hex')(b'foo')[0]

从Python 3.4开始,有一个不太尴尬的选项:

codecs.encode(b'foo', 'hex')

这些杂项编解码器也可以在它们自己的模块(base64,zlib,bz2,uu,quopri,binascii)中访问;API的一致性较差,但对于压缩编解码器,它提供了更多控制权。

Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

import codecs
codecs.getencoder('hex')(b'foo')[0]

Starting with Python 3.4, there is a less awkward option:

codecs.encode(b'foo', 'hex')

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.


回答 3

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

在Python 3.3中工作(因此是“ hex_codec”而不是“ hex”)。

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

works in Python 3.3 (so “hex_codec” instead of “hex”).


回答 4

该方法binascii.hexlify()将转换bytesbytes代表ascii十六进制字符串的字符串。这意味着输入中的每个字节将转换为两个ascii字符。如果您想要一个真实的结果str,那么您可以.decode("ascii")的结果得到结果。

我提供了一个说明它的片段。

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

从十六进制字符串"0a160a04"到可以回来了bytesbinascii.unhexlify("0a160a04")该还给b'\n\x16\n\x04'

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

I included an snippet that illustrates it.

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'


回答 5

好的,如果您只关心Python 3,以下答案会稍微超出范围,但是即使您未指定Python版本,此问题也是Google的第一个热门产品,因此这是一种适用于Python 2 Python 3的方法。

我也在解释这个问题是关于将字节转换为 str类型:即在Python 2上为bytes-y,在Python 3上为Unicode-y。

鉴于此,我知道的最佳方法是:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

假设您尚未激活unicode_literalsPython 2 的未来,以下断言对于Python 2或Python 3都是正确的:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(或者您可以''.join()用来省略字节之间的空格,等等。)

OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don’t specify the Python version, so here’s a way that works on both Python 2 and Python 3.

I’m also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.

Given that, the best approach I know is:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

The following assertion will be true for either Python 2 or Python 3, assuming you haven’t activated the unicode_literals future in Python 2:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(Or you can use ''.join() to omit the space between the bytes, etc.)


回答 6

可以使用格式说明符%x02来格式化并输出一个十六进制值。例如:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

it can been used the format specifier %x02 that format and output a hex value. For example:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

回答 7

python 3.8中的新增功能,您可以将定界符参数传递给hex函数,如本例所示

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

New in python 3.8, you can pass a delimiter argument to the hex function, as in this example

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex


回答 8

如果要将b’\ x61’转换为97或’0x61’,可以尝试以下操作:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

参考:https : //docs.python.org/3.5/library/struct.html

If you want to convert b’\x61′ to 97 or ‘0x61’, you can try this:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

Reference:https://docs.python.org/3.5/library/struct.html


在Python中将十六进制字符串转换为int

问题:在Python中将十六进制字符串转换为int

如何在Python中将十六进制字符串转换为int?

我可能将其命名为“ 0xffff”或“ ffff”。

How do I convert a hex string to an int in Python?

I may have it as “0xffff” or just “ffff“.


回答 0

如果没有 0x前缀,则需要显式指定基数,否则无法告诉:

x = int("deadbeef", 16)

使用 0x前缀,Python可以自动区分十六进制和十进制。

>>> print int("0xdeadbeef", 0)
3735928559
>>> print int("10", 0)
10

(您必须指定0作为基准才能调用此前缀猜测行为;省略第二个参数意味着假定基准为10。)

Without the 0x prefix, you need to specify the base explicitly, otherwise there’s no way to tell:

x = int("deadbeef", 16)

With the 0x prefix, Python can distinguish hex and decimal automatically.

>>> print int("0xdeadbeef", 0)
3735928559
>>> print int("10", 0)
10

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; omitting the second parameter means to assume base-10.)


回答 1

int(hexString, 16) 可以解决问题,并且可以使用和不使用0x前缀:

>>> int("a", 16)
10
>>> int("0xa",16)
10

int(hexString, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa",16)
10

回答 2

对于任何给定的字符串s:

int(s, 16)

For any given string s:

int(s, 16)

回答 3

在Python中将十六进制字符串转换为int

我可能有它"0xffff"或只是它"ffff"

要将字符串转换为int,请将字符串int与要转换的基数一起传递给。

两个字符串都可以通过以下方式进行转换:

>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535

int推断

如果您将0作为基数,int则将从字符串中的前缀推断基数。

>>> int(string_1, 0)
65535

如果没有十六进制前缀0xint没有足够的信息与猜测:

>>> int(string_2, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'

文字:

如果您要输入源代码或解释器,Python将为您进行转换:

>>> integer = 0xffff
>>> integer
65535

这将无法使用,ffff因为Python会认为您正在尝试编写合法的Python名称:

>>> integer = ffff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined

Python数字以数字字符开头,而Python名称不能以数字字符开头。

Convert hex string to int in Python

I may have it as "0xffff" or just "ffff".

To convert a string to an int, pass the string to int along with the base you are converting from.

Both strings will suffice for conversion in this way:

>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535

Letting int infer

If you pass 0 as the base, int will infer the base from the prefix in the string.

>>> int(string_1, 0)
65535

Without the hexadecimal prefix, 0x, int does not have enough information with which to guess:

>>> int(string_2, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'

literals:

If you’re typing into source code or an interpreter, Python will make the conversion for you:

>>> integer = 0xffff
>>> integer
65535

This won’t work with ffff because Python will think you’re trying to write a legitimate Python name instead:

>>> integer = ffff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined

Python numbers start with a numeric character, while Python names cannot start with a numeric character.


回答 4

在上述Dan的答案中加上:如果为int()函数提供了十六进制字符串,则必须将基数指定为16,否则它不会认为您给了它有效的值。对于字符串中不包含的十六进制数字,无需指定基数16。

print int(0xdeadbeef) # valid

myHex = "0xdeadbeef"
print int(myHex) # invalid, raises ValueError
print int(myHex , 16) # valid

Adding to Dan’s answer above: if you supply the int() function with a hex string, you will have to specify the base as 16 or it will not think you gave it a valid value. Specifying base 16 is unnecessary for hex numbers not contained in strings.

print int(0xdeadbeef) # valid

myHex = "0xdeadbeef"
print int(myHex) # invalid, raises ValueError
print int(myHex , 16) # valid

回答 5

最坏的方法:

>>> def hex_to_int(x):
    return eval("0x" + x)

>>> hex_to_int("c0ffee")
12648430

请不要这样做!

在Python中使用eval是不好的做法吗?

The worst way:

>>> def hex_to_int(x):
    return eval("0x" + x)

>>> hex_to_int("c0ffee")
12648430

Please don’t do this!

Is using eval in Python a bad practice?


回答 6

或者ast.literal_eval(这很安全,不像eval):

ast.literal_eval("0xffff")

演示:

>>> import ast
>>> ast.literal_eval("0xffff")
65535
>>> 

Or ast.literal_eval (this is safe, unlike eval):

ast.literal_eval("0xffff")

Demo:

>>> import ast
>>> ast.literal_eval("0xffff")
65535
>>> 

回答 7

格式化程序选项’%x’%对我来说似乎也可以在赋值语句中使用。(假设Python 3.0及更高版本)

a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100

The formatter option ‘%x’ % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)

Example

a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100

回答 8

如果您使用的是python解释器,则只需键入0x(您的十六进制值),解释器就会自动为您转换。

>>> 0xffff

65535

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

>>> 0xffff

65535

回答 9

处理十六进制,八进制,二进制,整数和浮点数

使用标准前缀(即0x,0b,0和0o),此函数会将任何合适的字符串转换为数字。我在这里回答了这个问题:https : //stackoverflow.com/a/58997070/2464381,但这是必需的功能。

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

Handles hex, octal, binary, int, and float

Using the standard prefixes (i.e. 0x, 0b, 0, and 0o) this function will convert any suitable string to a number. I answered this here: https://stackoverflow.com/a/58997070/2464381 but here is the needed function.

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

回答 10

在Python 2.7中,int('deadbeef',10)似乎不起作用。

以下对我有用:

>>a = int('deadbeef',16)
>>float(a)
3735928559.0

In Python 2.7, int('deadbeef',10) doesn’t seem to work.

The following works for me:

>>a = int('deadbeef',16)
>>float(a)
3735928559.0

回答 11

加上“ 0x”前缀,您也可以使用eval函数

例如

>>a='0xff'
>>eval(a)
255

with ‘0x’ prefix, you might also use eval function

For example

>>a='0xff'
>>eval(a)
255