1

After a bit of googling, nothing came up. I am manipulating sequence numbers for network packets and need the numbers to be of a fixed length. For example:

>>> 0000 + 1
1

Instead, I'd like the integer that is returned to be 0001. Are there any built-in commands for setting an integer of fixed length?

Edit: I do not need to print these integers, I need to actually manipulate them. I will need them to iterate but they must be fixed length so that they can be easily found in a networking protocol head file.

Ampage Grietu
  • 89
  • 1
  • 2
  • 10

2 Answers2

4

What you're asking doesn't make any sense. The integer 0011 and the integer 11 are exactly the same number.*

If you want to format them as strings to print them out or to search a text file, you can do that with, e.g., format(n, '04'). It doesn't matter whether you're formatting 11 or 0011, they're both the same number, and that number will format to the string '0011'.

If you want to convert them to big-endian 32-bit C-style unsigned integers, again, they're both the same number, and struct.pack('>I', n) will pack that number to the byte string b'\x00\x00\x00\x0b'.

If you want to add them modulo 10000, again, they're both the same number, and (n + 9990) % 10000 will give you 1.

No matter what operation you dream up, there will be no difference.


* Actually, in Python 2.x, number literals starting with 0 are treated as octal, not decimal, so 0011 is actually 9, not 11. And in 3.x numbers starting with 0 are a SyntaxError, to avoid the confusion caused by accidentally writing octal numbers. But forget all that. We're not talking about the Python number literals, we're talking about something even simpler here: the numbers themselves.

abarnert
  • 354,177
  • 51
  • 601
  • 671
2

Numbers don't have a "length", they're just numbers. The representation of a number as text, in a string, has a length. To convert numbers to strings in Python, use the format() function:

x = 1
s = "{:04d}".format(x)
print(s)
Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
  • Simpler to use the `format` function, as your text says, than the `str.format` method, as your example code does. – abarnert Nov 05 '14 at 01:02