up vote 1 down vote favorite

What is the write 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?

flag

67% accept rate

2 Answers

up vote 3 down vote

Use struct.

import struct

print struct.pack('L', len("some string")) # int to a (long) byte array
link|flag
+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. – tyndall Apr 28 '09 at 17:59
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). – sysrqb Apr 29 '09 at 3:15
up vote 1 down vote

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.

link|flag
+1 thanks. I wish I knew what the pure Python syntax would be... but I keep running into Python 3 documentation. – tyndall Apr 28 '09 at 4:36

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.