20.9k views
4 votes
Use Assembly PLEASE !!

Complete swap_bits function which swaps bits at odd and even positions of an integer (32 bits). In other words, every even position bit is swapped with the adjacent bit on the right side, and every odd position bit is swapped with the adjacent on the left side. For instance, bits 0 and 1 are swapped, bits 2 and 3 are swapped, and so on. It is not recommended to use loops or conditional statements for this part.

PART 2 (Swap Bits)
#
# You are given an 32-bits integer stored in $t0. You need swap the bits
# at odd and even positions. i.e. b31 <-> b30, b29 <-> b28, ... , b1 <-> b0
# The result must be stored inside $t0 as well.
swap_bits:
move $t0, $a0
############################## Part 2: your code begins here ###

############################## Part 2: your code ends here ###
move $v0, $t0
jr $ra


Example: if the given number is 23 (00010111), it should be converted to 43 (00101011). Note this example, we only use the lower 8 bits of a number, but your program will work on 32-bit numbers.


You can expect the input to your function in register $t0. The result must be stored inside $t0 as well.

1 Answer

2 votes

Answer:

See explaination

Step-by-step explanation:

swapBits(unsigned int):

push rbp

mov rbp, rsp

mov DWORD PTR [rbp-20], edi

mov eax, DWORD PTR [rbp-20]

and eax, -1431655766

mov DWORD PTR [rbp-4], eax

mov eax, DWORD PTR [rbp-20]

and eax, 1431655765

mov DWORD PTR [rbp-8], eax

shr DWORD PTR [rbp-4]

sal DWORD PTR [rbp-8]

mov eax, DWORD PTR [rbp-4]

or eax, DWORD PTR [rbp-8]

pop rbp

ret

__static_initialization_and_destruction_0(int, int):

push rbp

mov rbp, rsp

sub rsp, 16

mov DWORD PTR [rbp-4], edi

mov DWORD PTR [rbp-8], esi

cmp DWORD PTR [rbp-4], 1

jne .L5

cmp DWORD PTR [rbp-8], 65535

jne .L5

mov edi, OFFSET FLAT:_ZStL8__ioinit

call std::ios_base::Init::Init() [complete object constructor]

mov edx, OFFSET FLAT:__dso_handle

mov esi, OFFSET FLAT:_ZStL8__ioinit

mov edi, OFFSET FLAT:_ZNSt8ios_base4InitD1Ev

call __cxa_atexit

.L5:

nop

leave

ret

_GLOBAL__sub_I_swapBits(unsigned int):

push rbp

mov rbp, rsp

mov esi, 65535

mov edi, 1

call __static_initialization_and_destruction_0(int, int)

pop rbp

ret

User Wioleta
by
6.5k points