关于交换半字节的装配问题

时间:2019-04-11 16:43:52

标签: assembly x86 bit-manipulation

我正在从事一个项目,并且在Assembly(ASM)中具有以下代码

//Part #C - Swap half nibbles
    xor ebx,ebx                             //Clears out the staging register
    mov ecx,4
halfnibswap1_loop:                              //Will shift right side into staging register and reverse them
    shr al,1
    rcl bl,1
    loop halfnibswap1_loop
    shl bl,4                                    //Aligns the staging to left to shift them back (in the new reverse order)

    mov ecx,4
halfnibswap2_loop:                              //Will shifts staging back in, swapped
    shl bl,1
    rcl al,1
    loop halfnibswap2_loop

    mov ecx,4
halfnibswap3_loop :                             //Will shift left side into staging register and reverse them
    shl al,1
    rcr bl,1
    loop halfnibswap3_loop
    shr bl,4                                    //Aligns the staging to right to shift them back (in the new reverse order)

    mov ecx,4
halfnibswap4_loop:                              //Will shifts staging back in, swapped
    shr bl,1
    rcr al,1
    loop halfnibswap4_loop

我首先从BD(10111101)开始。我要的是E7(11100111)。
基本上,字节76543210必须为54761032。(交换相邻的位对。)

我的代码似乎可以正常工作,但是我认为这是不正确的,并且绝对没有效率。我该怎么做?

1 个答案:

答案 0 :(得分:4)

这是5条指令中的一种可能的实现方式:

lea ebx,[eax*4]   ; ebx = eax*4 (i.e. eax << 2): 76543210 -> 543210..
and bl,0xCC       ; 543210.. -> 54..10..
shr al,2          ; al >>= 2: 76543210 -> ..765432
and al,0x33       ; ..765432 -> ..76..32
or al,bl          ; al = 54761032