What do andi and ori do in this program?

.global main # makes label "main" globally known .text # Instructions follow .align 2 # Align instructions to 4-byte words main: movi r16,0x47 # Load the hexadecimal value 41 # to register r16 loop: mov r4,r16 # Copy to r4 from r16 nop # (later changed to call hexasc) nop # (later changed to mov r4,r2) movia r8,putchar # copy subroutine address to a register callr r8 # call subroutine via register addi r16, r16,1 # Add 1 to register r16 andi r16, r16, 0x7f # mask with 7 bits ori r16, r16, 0x20 # set a bit to avoid control chars br loop # Branch to loop .end # The assembler will stop reading here foo bar bletch # comes after .end - ignored 

I can understand everything, I think, except that in this case the two teams andi and ori . ori seems to make ASCII 20 positions print ahead, but why and how?

+4
source share
3 answers

andi and ori are bitwise operators:

To see the difference, refer to

 and $rd, $rs, $rt or $rd, $rs, $rt 

vs

 andi $rt, $rs, immed ori $rt, $rs, immed 

http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/bitwise.html

+2
source

andi with 0x7f deletes the most significant bit that is not used by ASCII (which uses only 7 bits or 0-128 to match characters). 0x7f is 0111 1111 in binary format. Since all AND with 0 (the most significant bit is 0, as you can see), 0, all AND with 1 remains unchanged, the operation deletes the most significant bit.

ori with 0x20 will only set the 6th bit (2 5 ). 0x20 - 0010 0000 in binary format. Since all ORs with 1 (the 6th bit, as you can see) are 1, and all ORs with 0 remain unchanged, this leads to the setting of the 6th bit.

As the commentary says, just in case r16 is initially less than 32 or in the case of r16> = 128 and <160, it will make the number> = 0x20. This does not mean that he will always add 0x20, though (for example, r16 was originally 32 --addi → 33 - andi → 33 --ori → 33).

As a side note, AND'ing with a constant (also called a mask) is usually used to extract a specific bit from the source data. And it will extract on any bit that the corresponding bit in the mask is 1.

OR'ing with a constant is usually used to set specific bit (s) to 1. It will set a bit whose corresponding bit in the mask is 1.

By the way, to set a specific bit to 0, you can AND with a constant that is 1, except for the bit you want to set. To switch certain bits, you can XOR with a constant with the corresponding bit 1, and the rest 0.

+4
source

Using and in an assembly is a way for the bit to be turned off. Consider:

 1101 and 0111 --------- 0101 

Only in the second and last columns do 1s exist at the top and bottom, effectively ensuring that the first bit is disabled.

Using 'or' in an assembly is a way to make sure the bit is turned on. consider the following issues:

 1101 or 0111 ---------- 1111 

The 1s on the bottom line ensures that no matter what the first number, the last three bits will be included.

+2
source

All Articles