views:

1938

answers:

2

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?

+1  A: 

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.

Ben Robbins
+1 thanks. I wish I knew what the pure Python syntax would be... but I keep running into Python 3 documentation.
tyndall
+3  A: 

Use struct.

import struct

print struct.pack('L', len("some string")) # int to a (long) byte array
sysrqb
+1. Sorry follow up question then the long data type is unlimited. http://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
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