fbence
fbence

Reputation: 2153

python converting hexadecimal binary to string

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.

Upvotes: 8

Views: 57186

Answers (4)

Andrew B
Andrew B

Reputation: 106

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

Upvotes: 7

furas
furas

Reputation: 142641

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'

Upvotes: 3

Daniel
Daniel

Reputation: 42758

A byte string is automatically a list of numbers.

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

Upvotes: 7

Jaroszewski Piotr
Jaroszewski Piotr

Reputation: 363

Not sure if you want this result, but try it

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

Upvotes: 6

Related Questions