交换字变量的字节(低/高)的过程
我有一个交换 Word 变量的字节(低/高)的过程(它与 System.Swap 函数执行相同的操作)。该过程在编译器优化关闭时有效,但在编译器优化打开时无效。 有人能帮我解决这个问题吗?
procedure SwapWord(VAR TwoBytes: word);
asm
Mov EBX, TwoBytes
Mov AX, [EBX]
XCHG AL,AH
Mov [EBX], AX
end;
I have this procedure that swaps the bytes (low/high) of a Word variable (It does the same stuff as System.Swap function). The procedure works when the compiler optimization is OFF but not when it is ON.
Can anybody help me with this?
procedure SwapWord(VAR TwoBytes: word);
asm
Mov EBX, TwoBytes
Mov AX, [EBX]
XCHG AL,AH
Mov [EBX], AX
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最快:
如果您也想反转 DWORD:
Fastest:
In case you want to reverse DWORD too:
如果不保存/恢复,则无法在 ASM 代码中使用 EBX 寄存器。您的代码的更正版本是
You can't use EBX register in ASM code without saving/restoring it. The corrected version of your code is
让我有点惊讶的是,没有人提到“绝对”“黑客”,它已经存在了十多年,但没有引起太多关注……无论如何,这是我的两分钱
I'm a bit surprised that no one mentioned the
absolute
"hack" which is around for more than a decade but doesn't get too much spotlight... anyways here's my two cents您是否考虑过使用编译器的
Swap
函数?如果没有,则不需要 ASM(并且 ASM 可能在 64 位 Delphi 中不可用)。你可以这么做
,当然,这个主题有“一百万”个变体。
并且,非常简单地,
或者
Have you considered using the compiler's
Swap
function?If not, you don't need ASM for this (and ASM will probably not be available in 64-bit Delphi). You can just do
and, of course, there are "a million" variations on this theme.
and, very briefly,
or
尽管 Serg 的答案肯定是正确的,正如对 Serg 答案的评论中指出的那样,但它效率不高。最快的显然是 Gabr 的答案中提供的代码,但由于您明确需要一个过程,而不是一个函数,因此以下将是 Serg 例程的首选版本:
[注 1:] Serg 的函数版本很可能会,不适用于即将推出的 x64 Delphi 编译器。假设 Embarcadero 坚持使用 Win64 调用约定(其中
@TwoBytes
将通过RCX
传递)的计划(Allen Bauer 在某处提到),此答案中提供的版本应该仍然可以在 x64 上运行。Although Serg's answer is certainly correct, as pointed out in comments to Serg's answer, it's not efficient. The fastest would clearly be the code provided in Gabr's answer, but since you explicitly want a procedure, not a function, the following would be the preferred version of Serg's routine:
[Note1:] Serg's version of the function will, in all likelihood, not work for the upcoming x64 Delphi compiler. Assuming Embarcadero stick to their plan (mentioned somewhere by Allen Bauer) of using the Win64 calling convention (where
@TwoBytes
would be passed viaRCX
) the version provided in this answer should still work on x64.