fm_user8
fm_user8

Reputation: 438

Converting a hex value of a string to an Ascii character with a hex value

Specifically in Python 2.4, which is unfortunately old, I need to convert a length into hex value. Length of 1 would be '\x00\x01' while a length of 65535 would be '\xFF\xFF'.

import struct

hexdict = {'0':'\x00\x00', '1':'\x00\x01', '2':'\x00\x02', '3':'\x00\x03', '4':'\x00\x04', '5':'\x00\x05', '6':'\x00\x06', '7':'\x00\x07', '8':'\x00\x08', '9':'\x00\x09', 'a':'\x00\x0a', 'b':'\x00\x0b', 'c':'\x00\x0c', 'd':'\x00\x0d', 'e':'\x00\x0e', 'f':'\x00\x0f'}



def convert(int_value): # Not in original request
    encoded = format(int_value, 'x')
    length = len(encoded)
    encoded = encoded.zfill(length+length%2)
    retval = encoded.decode('hex')
    if x < 256:
        retval = '\x00' + retval
    return retval 



for x in range(16):
    print hexdict[str(hex(x)[-1])] # Original, terrible method
    print convert(x) # Slightly better method
    print struct.pack(">H", x) # Best method

Aside from having a dictionary like above, how can I convert an arbitrary number <= 65535 into this hex string representation, filling 2 bytes of space?

Thanks to Linuxios and an answer I found while waiting for that answer, I have found three methods to do this. Obviously, Linuxios' answer is the best, unless for some reason importing struct is not desired.

Upvotes: 1

Views: 446

Answers (1)

Linuxios
Linuxios

Reputation: 35788

Using Python's built-in struct package:

import struct
struct.pack(">H", x)

For example, struct.pack(">H", 1) gives '\x00\x01' and struct.pack(">H", 65535) gives '\xff\xff'.

Upvotes: 1

Related Questions