Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to BSWAP the lower 32-bit of 64-bit register?

I've been looking for the answer for how to use BSWAP for lower 32-bit sub-register of 64-bit register. For example, 0x0123456789abcdef is inside RAX register, and I want to change it to 0x01234567efcdab89 with a single instruction (because of performance).

So I tried following inline function:

#define BSWAP(T) {  \
    __asm__ __volatile__ (  \
            "bswap %k0" \
            : "=q" (T)  \
            : "q" (T)); \
}

And the result was 0x00000000efcdab89. I don't understand why the compiler acts like this. Does anybody know the efficient solution?

like image 465
user25683 Avatar asked Oct 07 '08 02:10

user25683


People also ask

Are there 64-bit registers?

Registers. x64 extends x86's 8 general-purpose registers to be 64-bit, and adds 8 new 64-bit registers. The 64-bit registers have names beginning with "r", so for example the 64-bit extension of eax is called rax. The new registers are named r8 through r15.

Are registers 32 bits?

A register is a part of the processor that can hold a bit pattern. On the MIPS, a register holds 32 bits. There are many registers in the processor, but only some of them are visible in assembly language. The others are used by the processor in carrying out its operations.

What does bswap do?

The BSWAP (byte swap) instruction reverses the byte order in a 32-bit register operand. Bit positions 0 through 7 are exchanged with 24 through 31, and bit positions 8 through 15 are exchanged with 16 through 23. Executing this instruction twice in a row leaves the register with the same value as before.

What are 64-bit registers?

A 64-bit processor uses internal registers -- temporary storage locations within the processor -- that are 64 bits wide. This typically corresponds to an address bus and data bus that are also 64 bits wide.


1 Answers

Ah, yes, I understand the problem now:

the x86-64 processors implicitly zero-extend the 32-bit registers to 64-bit when doing 32-bit operations (on %eax, %ebx, etc). This is to maintain compatibility with legacy code that expects 32-bit semantics for these registers, as I understand it.

So I'm afraid that there is no way to do ror on just the lower 32 bits of a 64-bit register. You'll have to do use a series of several instructions...

like image 190
Dan Lenski Avatar answered Oct 10 '22 21:10

Dan Lenski