以十六进制字符串重新排序字节顺序(python) [英] reorder byte order in hex string (python)
问题描述
我想在python中构建一个小格式化程序,将数字
值嵌入到十六进制字符串行中。
它是我的格式化程序,并且应该合理快速到
格式超过100行/秒(每行大约〜100个字符)。
下面的代码应该举一个例子我目前被阻止。
'data_string_in_orig'显示给定的输入格式。它必须为每个单词交换
字节。需要从'data_string_in_orig'交换到
'data_string_in_swapped'。最后,我需要结构
访问,如图所示。预期结果在评论中。
预先致谢
Wolfgang R
#!/ usr / bin / python
导入binascii
导入结构
##'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)
退出(0)
array.arrays
有一个 byteswap方法:
$ b $ pre $ 导入binascii
导入结构
导入数组
x = binascii.unhexlify (b62e000052e366667 a66408d')
y = array.array('h',x)
y.byteswap()
s = struct.Struct('< Id')
print(s。 unpack_from(y))
#(46638,943.2999999994321)
code> h 在中选择array.array('h',x)
是因为它告诉数组。 array
将 x
中的数据视为2字节短数组。重要的是每个项目都被认为是2个字节长。 H
,表示2字节无符号短符号,工作正常。
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)
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('<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.
这篇关于以十六进制字符串重新排序字节顺序(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!