Swap bits (or just access them) in assembly x86 -


i'm going come out disclaimer , homework problem. don't want solve it, want clarification.

the exact problem this:

write function swap odd , bits in integer few instructions possible (e.g., bit 0 , bit 1 swapped, bit 2 , bit 3 swapped, , on).

it hints no conditional statements required.

i kind of looked , discovered if somehow separate , odd bits can use shifts accomplish this. don't understand how manipulate individual bits. in python (programming language i'm used to) it's easy index operator can number[0] example , can first bit. how do assembly?

edit: @jotik, help. implemented this:

mov edi, ebx , edi, 0x5555555555555555 shl edi, 1 mov esi, ebx , esi, 0xaaaaaaaaaaaaaaaa shr esi, 1 or edi, esi mov eax, edi 

and when saw | operator, thinking or ||. silly mistake.

in assembly 1 can use bit masks other bitwise operations archive result.

result = ((odd-bit-mask & input) << 1) | ((even-bit-mask & input) >> 1) 

where odd-bit-mask value odd bits set (1) , bits unset (0); , even-bit-mask value bits set (1) , odd bits unset. 64-bit values, odd , bit masks (in hexadecimal notation) 0x0x5555555555555555 , 0xaaaaaaaaaaaaaaaa respectively.

so pseudocode of assembly algorithm similar following:

oddbits  = input & 0x5555555555555555 oddbits  = oddbits << 1 evenbits = input & 0xaaaaaaaaaaaaaaaa evenbits = evenbits >> 1 result   = oddbits | evenbits 

where & bitwise , operation, | bitwise or operation, << , >> bitwise shift left , bitwise shift right operations respectively.

ps: can find other useful bit manipulation tricks on sean eron anderson's bit twiddling hacks webpage.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -