Reputation: 35
I have a small server sending raw data with a socket in python which only accepts bytearrays as input. In this bytearray I have to include mac-addresses. These mac-addresses come from a json-file, imported as a string. e.g "00 11 22 33 44 55" (actually without the spaces)
what i am searching for is an easy way of encoding this string into a bytearray. so the first byte should be 00, second 11 and so on.
all "solutions" i have found will encode any string into a byte-array, but this isn't what i want, because it will split up my mac-address further because they will encode for example 0, then 0, then 1, then 1 and so on so my 6-byte mac-address becomes a 12 byte encoded byte-array.
Is there any built-in function I can use or do I have to create my own function to do this?
SOLUTION: Thx to you all and Arnial for providing the most easy answer. The thing is, all these answers i have more or less tried out with no effect before BUT My problem was not the type of the return-type of these methods (which my socket always refused to send), it was actually the length of the message i tried to send. The socket refuses to send messages shorter then 12 bytes (source/destination mac-addresses), but i only ever tried a short message with this example mac-address converted with one of the here presented methods.
So thank you all for your help!
Upvotes: 1
Views: 1404
Reputation: 1441
Your conversion isn't so literal as you think.
String "00112233445566" is 12 characters long, this why it converts to 12 bytes array.
Your mac looks like hex encoded byte string, so probably you can use this:
bytes.fromhex( "001122334455" )
It will create byte sequence that starts with zero byte, then 0x11 (17), than 0x22 (34) ...
Upvotes: 2
Reputation: 8078
Just split the string up into chunks of 2 characters, and interpret the hex value.
def str2bytes(string):
return tuple(int(string[i:i+2], 16) for i in range(0, len(string), 2))
print str2bytes("001122334455") #(0, 17, 34, 51, 68, 85)
If you are looking to have a string version of the above then:
def str2bytes(string):
return "".join(chr(int(string[i:i+2], 16)) for i in range(0, len(string), 2))
print str2bytes("001122334455") #Encoded string '\x00\x11"3DU' same as '\x00\x11\x22\x33\x44\x55'
Upvotes: 1
Reputation: 168596
https://docs.python.org/3/library/binascii.html#binascii.a2b_hex
import binascii
def str2bytes(string):
return binascii.a2b_hex(string)
print(str2bytes("001122334455"))
Upvotes: 0
Reputation: 280227
This is actually built-in! It's binascii.unhexlify
.
import binascii
binascii.unhexlify('001122334455')
Upvotes: 0