python十六进制排序_以十六进制字符串重新排序字节顺序(python)

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('

unpacked_data = s.unpack_from(packed_data, 0)

print 'Unpacked Values:', unpacked_data

## Unpacked Values: (46638, 943.29999999943209)

exit(0)

解决方案

array.arrays have a byteswap method:

import binascii

import struct

import array

x = binascii.unhexlify('b62e000052e366667a66408d')

y = array.array('h', x)

y.byteswap()

s = struct.Struct('

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值