I know this question has been asked before, and some of the suggestions seem to be about needing a b to make the string a byte literal. However, im passing hex code to the function as 0x414243 to save it as ABC.
def _pack(_data, size):
numofbytes = size/8
print("Chars Expected: " + str(numofbytes))
formatString = "{}s".format(int(numofbytes))
print("Formatted String:" + formatString)
struct.pack(formatString,_data)
_pack(0x414243,24)
I'm not sure what to change here, im wondering if its a problem with how im using formatstring variable. I want the function to be able to work out how many chars are in the passed data from the size and in this case 24 bits = 3 bytes so it formats 3s and passes 0x414243 to convert to ABC.
Can anyone advise how to get past the error.
As the error message says,
struct.pack()wants a group of bytes and you're giving it an integer.If you want to be able to pass the data in as an integer, convert it to bytes before packing it:
Or just pass the data in as bytes when you call it:
If you have a string containing hexadecimal, such as
"0x414243", you can convert it to an integer, then on to bytes:You might use
isinstance()to allow your function to accept any of these formats:By the way, your calculation of the number of bytes will produce a floating-point answer if
sizeis not a multiple of 8. A fractional number of bytes is an error. To address this:The
+ bool(size % 8)bit adds one to the result of the integer division if there are any bits left over.