Ian004
Ian004

Reputation: 195

How to print little endian hex number of varying sizes?

Im trying to write to a file a series of little endian hex numbers (with padded zeros, and no '0x' precursor).

The size of these numbers is determined by the user. Here is what I have so far:

file.write( format( struct.unpack( '<I', struct.pack( '>I', i ) ) [0], '08x' ))

where 'i' is the current iteration of a for-loop.

So far this only prints 4-byte numbers, denoted by the I. If the user will define the size, how do I write the number? If user wants 6-bytes its should write:

010000000000, 020000000000, etc

If user wants 2-bytes it should write:

0100, 0200, etc

EDIT: Also when I change the '08x' to say '012x' I get:

0000000001000000

so if I want a 8-byte number I can't just change the '08x' part...

Upvotes: 0

Views: 456

Answers (1)

Stefan Pochmann
Stefan Pochmann

Reputation: 28646

Not sure this is the best way, but it works (if I understand your requirement):

def f(number, length):
    s = '{:0{}x}'.format(number, length*2)
    return ''.join(s[i-2:i] for i in range(len(s), 0, -2))

for i in range(20):
    print(f(i, 6))

Output:

000000000000
010000000000
020000000000
030000000000
040000000000
050000000000
060000000000
070000000000
080000000000
090000000000
0a0000000000
0b0000000000
0c0000000000
0d0000000000
0e0000000000
0f0000000000
100000000000
110000000000
120000000000
130000000000

Upvotes: 1

Related Questions