Reverse EAX Byte Order

Example: 0xAABBCCDDturn into0xDDCCBBAA

My program crashes due to an Access Violation exception in the first XOR operation.

There seems to be a better naive solution using shift or rotation, but here is the code anyway:

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

      .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

What am I doing wrong here? Is there a better solution for this?

+2
source share
3 answers

Why not just:

 mov  eax, 0AABBCCDDh
 bswap eax

I'm not sure what you are trying to do in your program, but you can say that it is actually trying to make the CPU (but it cannot, and this is why it crashes):

This:

XOR BYTE PTR [eax], al 

xor AL ( ) 0AABBCCDDh ( EAX). - , , GPF.

bswap ( X.J):

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

...

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

, ? , X.J ( , - ) , , !:)

+3

, rol:

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

I believe that in most cases this will be slightly faster than using the instructions xchg, although I see no reason not to just use bswapone that is cleaner and most likely faster.

+1
source

Source: https://habr.com/ru/post/1669800/


All Articles