Krishna
Krishna

Reputation: 49

Convert bytes to string or number in Python

I want to get the first 6 bytes from payload as a single number or string.

for byte_pos in range(6):
   byte_content  = ord(payload[byte_pos])

Assume the payload is 1 2 3 4 5 6,

for byte_pos in range(6):
   print ord(payload[byte_pos])

This will result as follows, 0x1 0x2 0x3 0x4 0x5 0x6

But what I need is a single number/string like 123456. How to combine these single numbers to make 123456?

How to convert these 6 byte_contents to a single number or string.

Upvotes: 0

Views: 532

Answers (3)

Krishna
Krishna

Reputation: 49

dst_mac = ''
for byte_pos in range(6):
    dst_mac = dst_mac + str(hex((ord(payload[byte_pos])))[2:])
print dst_mac

This way, it worked.

Thank you

Upvotes: 0

Chocorean
Chocorean

Reputation: 878

If you are reading bytes, it means you are reading integers from 0 to 255. So you can turn those numbers quickly to base-10 like this : int(str(byte), 2)

If you want to turn bytes into characters, you might use the chr() function : char = chr(int(str(byte), 2))

Upvotes: 2

RWIN
RWIN

Reputation: 63

If you are working with Python 2.x here's an answer (if I understood what you want to do) :

payload  = bytearray(b'\x41\x42\x43') #Hex code for ABC
final_string = ''


for byte_pos in range(3):
   byte_content  = chr(payload[byte_pos])
   #print byte_content
   final_string = final_string + byte_content
   print final_string

Output will be :

A
AB
ABC

Upvotes: 1

Related Questions