2

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 2

4

Use struct.

import struct

print struct.pack('L', len("some string")) # int to a (long) byte array
Sign up to request clarification or add additional context in comments.

3 Comments

+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.
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).
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.
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.