skeggse
skeggse

Reputation: 6323

Integer to Unique String

There's probably someone else who asked a similar question, but I didn't take much time to search for this, so just point me to it if someone's already answered this.

I'm trying to take an integer (or long) and turn it into a string, in a very specific way.

The goal is essentially to split the integer into 8-bit segments, then take each of those segments and get the corresponding ASCII character for that chunk, then glue the chunks together.

This is easy to implement, but I'm not sure I'm going about it in the most efficient way.

>>> def stringify(integer):
        output = ""
        part = integer & 255
        while integer != 0:
                output += chr(part)
                integer = integer >> 8
        return output
>>> stringify(10)
'\n'
>>> stringify(10 << 8 | 10)
'\n\n'
>>> stringify(32)
' '

Is there a more efficient way to do this? Is this built into Python?

EDIT:

Also, as this will be run sequentially in a tight loop, is there some way to streamline it for such use?

>>> for n in xrange(1000):  ## EXAMPLE!
        print stringify(n)
...

Upvotes: 0

Views: 271

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

struct can easily do this for integers up to 64 bits in size. Any larger will require you to carve the number up first.

>>> struct.pack('>Q', 12345678901234567890)
'\xabT\xa9\x8c\xeb\x1f\n\xd2'

Upvotes: 3

Related Questions