What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing?
2 Answers
Use struct.
import struct
print struct.pack('L', len("some string")) # int to a (long) byte array
3 Comments
BuddyJoe
+1. Sorry follow up question then the long data type is unlimited. docs.python.org/library/stdtypes.html I need the value (length) to be stored in 6 bytes. What is the best way to account for this. I need to pad the bytes on smaller numbers.
rmmh
The datatypes used by the struct module are not the same ones used in Python. In this case 'long' is 4 bytes. 6 bytes is a strange length for an integer, but you could accomplish it with something like struct.pack('<Q', len("some string")[:6]. I'd recommend using 4 bytes (just 'L'), though, as you're not going to have strings with more than 2 billion characters (I hope).
parvus
Wouldn't it be better to do something like [ ord(x) for x in struct.pack('L', <YOUR_NUMBER>) ]? If I use this to convert the current epoch I get a string like 'e0\xf1U', using ord I get [100, 48, 241, 85] which looks way more usable.
using .Net:
byte[] buffer = System.BitConverter.GetBytes(string.Length)
print System.BitConverter.ToString(buffer)
That will output the bytes as hex. You may have to clean up the syntax for IronPython.
1 Comment
BuddyJoe
+1 thanks. I wish I knew what the pure Python syntax would be... but I keep running into Python 3 documentation.