8

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.

3
  • 1
    What is your input and what is the intended output? Commented Jan 11, 2017 at 19:38
  • 2
    b means bytes, not binary. \x00 is not string 0 but char with code 0 which can't be displayed so Python shows its code. Commented Jan 11, 2017 at 19:42
  • what result do you expect with b"\x0F" - "F" or "15" ? Commented Jan 11, 2017 at 19:48

4 Answers 4

7

A byte string is automatically a list of numbers.

input_bytes = b"\x00\x01"
output_numbers = list(input_bytes)
Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

6

Not sure if you want this result, but try it

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

2 Comments

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

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.