-1

Assuming I am creating a function called swap(int)

Calling it with int = 0xAABBCCDD, Expected return 0xDDCCBBAA. In what way can I access the memory in assembly to control it bit by bit rather than 4 bits at a time. If it's not possible, in what way can I swap the values?

Thanks

Abhishek
  • 2,925
  • 4
  • 34
  • 59
  • 2
    Assembly language: Which one? Mips? ARM? x86? x64? You say "inline assembly": For what compiler? gcc? MSVC? – David Wohlferd Jun 13 '17 at 05:26
  • 1
    You want bit wise but your example shows 4 bits at a time. – Ajay Brahmakshatriya Jun 13 '17 at 05:42
  • This is dependent on which platform you're targeting and its calling convention. More detail required. – Colin Jun 13 '17 at 07:10
  • 1
    Your examples shows swapped bytes, not bits. One bit is 0 or 1. One byte is 8 bits (0..255, or 00..FF in hexadecimal). If you would swap bits, then 0xAABBCCDD => 0xBB33DD55. There are many libraries and functions dealing with endianness (swapping of bytes, not bits), so don't inline asm for that, just use one of the provided solutions. – Ped7g Jun 13 '17 at 08:28
  • 1
    Possible duplicate of [How do I convert between big-endian and little-endian values in C++?](https://stackoverflow.com/questions/105252/how-do-i-convert-between-big-endian-and-little-endian-values-in-c) – Ped7g Jun 13 '17 at 08:28

1 Answers1

1

For the purpose of this answer, I'm going to assume x86 or x86_64 and that you are really looking for an assembly answer. Also, since I misread the question the first time, I'm providing two answers for you... :)

What that context, there are no instructions to allow you to deal with just a few bits directly, though there are the various register names to allow you to get to things as small as a single byte. Otherwise, bit manipulation would require AND and OR with masking.

For your specific case, though, there is an alternative. Consider this:

mov eax, 0xAABBCCDD

We now have your value in eAX. If you want to reverse the order of the bytes within that register, the BSWAP instruction is for you:

bswap eax

This will result in EAX containing 0xDDCCBBAA, which seems to be what you've asked.

On the other hand, if you want to switch the bits to move the 0xAABB to the lower two bytes, you can do this:

ror eax, 16

This will rotate the 32 bit value to the right 16 bits. In other words, EAX will now contain 0xCCDDAABB, which was your goal.

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67