EAX寄存器的反向字节顺序

时间:2013-10-14 23:15:24

标签: assembly x86 masm endianness masm32

示例:0xAABBCCDD将变为0xDDCCBBAA

由于第一次XOR操作中的访问冲突异常,我的程序崩溃了。

似乎有一个更好的天真解决方案,使用移位或旋转,但无论如何,这是代码:

  ;; #########################################################################

      .486
      .model flat, stdcall
      option casemap :none   ; case sensitive

;; #########################################################################

      include \masm32\include\masm32.inc
      include \masm32\include\kernel32.inc

      includelib \masm32\lib\kernel32.lib
    includelib \masm32\lib\masm32.lib


.code
;; The following program will flip the sequence of the bytes in the eax
;; example : 0xAABBCCDD will turn into 0xDDCCBBAA
start:
MOV eax, 0AABBCCDDh 
XOR BYTE PTR [eax], al ;; Swap first byte and last byte
XOR al, BYTE PTR [eax]
XOR BYTE PTR [eax], al 
XOR BYTE PTR [eax+1], ah ;; Swap 2nd byte of eax and 3rd byte
XOR ah, BYTE PTR [eax+1]
XOR BYTE PTR [eax+1], ah
end_prog:
    ;;Exit the program, eax is the exit code
    push eax
    call ExitProcess
END start

我在这里做错了什么?有没有更好的解决方案?

3 个答案:

答案 0 :(得分:15)

为什么不简单:

 mov  eax, 0AABBCCDDh
 bswap eax

我不确定你在程序中尝试做什么,但可以说出CPU实际尝试做什么(但不能,这就是崩溃的原因):

这一个:

XOR BYTE PTR [eax], al 

尝试计算寄存器AL(字节大小)中的值的xor运算和地址0AABBCCDDh(EAX寄存器的内容)的内存中的字节值。只要在该地址上没有OS分配任何内存,程序就会崩溃。

不使用bswap进行正确的字节交换如下(感谢X.J):

    xchg  ah, al
    ror   eax, 16
    xchg  ah, al.

答案 1 :(得分:3)

怎么'回合......

    mov eax, 0AABBCCDDh
    xchg al, ah ; 0AABBDDCCh
    rol eax, 16 ; 0DDCCAABBh
    xchg al, ah ; 0DDCCBBAAh

那会不会在一个寄存器中执行所需的操作吗?我看到X.J已经发布了(向左旋转,向右旋转 - 同样的结果)要快速击败你们! :)

答案 2 :(得分:2)

仅使用rol指令的替代解决方案:

mov eax,0xAABBCCDDh
rol ax,8            ; 0AABBDDCCh
rol eax,16          ; 0DDCCAABBh
rol ax,8            ; 0DDCCBBAAh

我相信,在大多数情况下,这将比使用xchg指令快得多,尽管我认为没有理由不简单地使用bswap,它更干净并且可能更快。

相关问题