Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
fbence Avatar asked Jun 06 '26 13:06

fbence


2 Answers

A byte string is automatically a list of numbers.

input_bytes = b"\x00\x01"
output_numbers = list(input_bytes)
like image 185
Daniel Avatar answered Jun 09 '26 02:06

Daniel


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
like image 28
Andrew B Avatar answered Jun 09 '26 02:06

Andrew B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!