python converting hexadecimal binary to string

27,584

Solution 1

Not sure if you want this result, but try it

output = [str(ord(x)) for x in output]

Solution 2

A byte string is automatically a list of numbers.

input_bytes = b"\x00\x01"
output_numbers = list(input_bytes)

Solution 3

Are you just looking for something like this?

for x in range(0,8):
    (x).to_bytes(1, byteorder='big')

Output is:

b'\x00'
b'\x01'
b'\x02'
b'\x03'
b'\x04'
b'\x05'
b'\x06'
b'\x07'

Or the reverse:

byteslist = [b'\x00',
b'\x01',
b'\x02',
b'\x03',
b'\x04',
b'\x05',
b'\x06',
b'\x07']

for x in byteslist:
    int.from_bytes(x,byteorder='big')

Output:

0
1
2
3
4
5
6
7

Solution 4

If you wiil need to convert b"\x0F" into F then use

print( hex(ord(b'\x0F'))[2:] )

or with format()

print( format(ord(b'\x0F'), 'X') )    # '02X' gives string '0F'
print( '{:X}'.format(ord(b'\x0F')) )  # '{:02X}' gives string '0F'
Share:
27,584
fbence
Author by

fbence

I guess I'm a data scientist or something like that at the Department of Ethology, Eötvös Loránd University in Budapest.

Updated on January 12, 2020

Comments

  • fbence
    fbence over 4 years

    I am using python3.5 and I wish to write output I get in hexadecimal bytes (b'\x00', b'\x01' etc) to python strings with \x00 -> 0 and \x01 -> 1 and I have this feeling it can be done easily and in a very pythonic way, but half an hour of googling still make me think the easiest would be to make a dictionary with a mapping by hand (I only actually need it from 0 to 7).

    Input    Intended output
    b'\x00'  0 or '0'
    b'\x01'  1 or '1'
    

    etc.

  • furas
    furas over 7 years
    nice but there will be problem with \x0F and similar ;)
  • Admin
    Admin over 7 years
    well... he said "I only actually need it from 0 to 7" :)