-1

I've been searching for an equivalent bswap instruction for 64 bit, but I did not find anything yet.

Let's say I have the following in a register RAX:

mov rax, 0x666E69

After swaping the values the register RAX should contain the following:

rax = 0x696E6600

I already tried with shl, shr, rol, and ror but nothing worked. Can you please help me ? Thank you.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
kannzzmm2
  • 131
  • 7
  • 1
    If you wanted to swap 64 bits I would expect input 666E69h to result in 696E6600_00000000h. Which one is it? – ecm Nov 01 '20 at 21:24
  • If you can't do it in one instruction, then use more than one instruction. – Erik Eidt Nov 01 '20 at 21:29
  • @ecm the one you provided is correct, I made a mistake I used as a example bwsap with a 32bit register eax – kannzzmm2 Nov 01 '20 at 21:46
  • @ErikEidt can you give me more details please ? – kannzzmm2 Nov 01 '20 at 21:47
  • 1
    [edit] your question to fix the expected input and output. Anyway, `bswap` works with 32 and 64 bit too. Does neither of those produce the result you want? – Jester Nov 01 '20 at 22:52

1 Answers1

1

bswap eax will reverse the low 4 bytes of RAX, zeroing the top 4 bytes of RAX as part of writing the result to EAX. 32-bit operand-size is always available, you don't have to use 64-bit operand-size in 64-bit mode. Look at any compiler output for code using int and you'll see 32-bit registers being used. See also The advantages of using 32bit registers/instructions in x86-64

In fact bswap r32 is faster (1 uop, 1c latency) than bswap r64 (2 uops, 2c latency) on mainstream Intel (including even Ice Lake) https://uops.info/

The low 4 bytes forward and reverse are
00 66 6E 69 input
69 6E 66 00 32-bit bswap result

That gives the result you say you want, for this input. If you have some other requirement for larger inputs with non-zero high halves, say so. (If you have SSSE3, you can do an arbitrary byte shuffle on an XMM register; worth considering if a bswap r32 or bswap r64 isn't what you want.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847