如何交换十六进制字节字符串中的相邻字节(使用或不使用正则表达式)
给定字符串(或具有偶数个单词对的任何长度字符串): “12345678”
我如何交换相邻的“单词”?
我想要的结果是 “34127856”
此外,完成后我需要交换多头。 我想要的结果是: “78563412”
Given the string (or any length string with an even-number of word pairs):
"12345678"
How would I swap adjacent "words"?
The result I want is
"34127856"
As well as, when that's done I need to swap the longs.
The result I want is:
"78563412"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正则表达式方法:
编辑:
然而,这绝对不是 Python 中最快的方法——这是人们发现这些事情的方法:首先,将所有“竞争”方法写入一个模块,这里我将其称为
'swa.py'...:
请注意,我设置了
s
并尝试了两种方法来进行快速健全性检查,以确保它们实际上计算出相同的结果 - 一般来说,对于这种类型来说,这是一种很好的做法“面对面的表演赛”!然后,在 shell 提示符处,使用
timeit
,如下所示:...您发现在这种情况下,无 RE 方法的速度大约快 4 倍,这是值得优化的。一旦您有了这样的“测量工具”,当然,如果在此操作中需要“真正的速度”,就可以轻松地尝试进一步的替代方案和调整以进一步优化。
编辑:例如,这是一种更快的方法(添加到相同的
swa.py
,最后一行print fast(s)
当然;-):这给出:
大约 5.6 微秒,低于最简单的无 RE 方法的大约 9.8 微秒,是另一个可能值得的微优化。
当然,等等——有一个古老的(伪)定理说任何程序都可以缩短至少一个字节,至少加快一纳秒......;-)
编辑:为了“证明”伪定理,这里有一个完全不同的方法(替换 swa.py 的末尾)...:
这给出了:
进一步可能值得加速。
A regex approach:
Edit:
However, this is definitely not the fastest approach in Python -- here's how one finds out about such things: first, write all "competing" approaches into a module, here I'm calling it
'swa.py'
...:Note that I set
s
and try out the two approaches for a fast sanity check that they're actually computing the same result -- good practice, in general, for this kind of "head to head performance races"!Then, at the shell prompt, you use
timeit
, as follows:...and you find that in this case the RE-less approach is about 4 times faster, a worthwhile optimization. Once you have such a "measurement harness" in place, it's also easy to experiment with further alternative and tweaks for further optimization, if there is any need for "really blazing speed" in this operation, of course.
Edit: for example, here's an even faster approach (add to the same
swa.py
, with a final line ofprint faster(s)
of course;-):This gives:
About 5.6 microseconds, down from about 9.8 for the simplest RE-less approach, is another possibly-worthwhile micro-optimization.
And so on, of course -- there's an old folk (pseudo)theorem that says that any program can be made at least one byte shorter and at least one nanosecond faster...;-)
Edit: and to "prove" the pseudotheorem, here's a completely different approach (replace the end of
swa.py
)...:This gives:
for a further possible-worthy speedup.
仅对于字符串“12345678”,
您可以将其设置为通用函数来执行可变长度字符串。
输出
just for the string "12345678"
you can make it to a generic function to do variable length string.
output
如果你想进行字节顺序转换,请使用Python的struct模块 在原始二进制数据上。
如果这不是您的目标,这里有一个简单的示例代码来重新排列一个 8 个字符的字符串:
If you want to do endianness conversion, use Python's struct module on the original binary data.
If that is not your goal, here's a simple sample code to rearrange one 8 character string:
我正在使用以下方法:
对我有用!
I'm using the following approach:
works for me!