reorder byte order in hex string (python)
Question: I want to build a small formatter in python giving me back the numeric values
embedded in lines of hex strings.

It is a central part of my formatter and should be reasonable fast to format
more than 100 lines/sec (each line about ~100 chars).

The code below should give an example where I'm currently blocked.

'data_string_in_orig' shows the given input format. It has to be byte swapped
for each word. The swap from 'data_string_in_orig' to 'data_string_in_swapped'
is needed. In the end I need the structure access as shown. The expected
result is within the comment.

Thanks in advance Wolfgang R

    
    
    #!/usr/bin/python
    
    import binascii
    import struct
    
    ## 'uint32 double'
    data_string_in_orig    = 'b62e000052e366667a66408d'
    data_string_in_swapped = '2eb60000e3526666667a8d40'
    print data_string_in_orig
    
    packed_data = binascii.unhexlify(data_string_in_swapped)
    s = struct.Struct('<Id')
    unpacked_data = s.unpack_from(packed_data, 0)  
    print 'Unpacked Values:', unpacked_data
    
    ## Unpacked Values: (46638, 943.29999999943209)
    
    exit(0)
    


Answer: `array.arrays` have a [byteswap
method](http://docs.python.org/2/library/array.html#array.array.byteswap):

    
    
    import binascii
    import struct
    import array
    x = binascii.unhexlify('b62e000052e366667a66408d')
    y = array.array('h', x)  
    y.byteswap()
    s = struct.Struct('<Id')
    print(s.unpack_from(y))
    
    # (46638, 943.2999999994321)
    

The `h` in `array.array('h', x)` was chosen because it tells `array.array` to
regard the data in `x` as an array of 2-byte shorts. The important thing is
that each item be regarded as being 2-bytes long. `H`, which signifies 2-byte
unsigned short, works just as well.

