Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
909 views
in Technique[技术] by (71.8m points)

assembly - Reverse byte order of EAX register

Example: 0xAABBCCDD will turn into 0xDDCCBBAA

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

It seems like there's a better naive solution, using shifting or rotating, but anyways, here's the code:

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

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

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

      include masm32includemasm32.inc
      include masm32includekernel32.inc

      includelib masm32libkernel32.lib
    includelib masm32libmasm32.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 any better solution for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why not simply:

 mov  eax, 0AABBCCDDh
 bswap eax

I am not sure what you are trying to do in your program, but can say what the CPU actually tries to do (but can't and that is why crashes):

This one:

XOR BYTE PTR [eax], al 

Tries to compute an xor operation of the value in the register AL (byte sized) and a value of the byte in memory at address 0AABBCCDDh (the content of EAX register). As long as on this address there is no any memory allocated by the OS, the program crashes with GPF.

The proper byte swapping without using bswap is the following (Thanks to X.J):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...