andi
lyszt.net covers andi and other RISC-V instructions in more detail.
Encoding format
Description
andi performs bitwise AND with a constant. and takes two registers, but andi takes a register and an immediate, a fixed value encoded in the instruction. The i stands for immediate. The AND rule is unchanged: a result bit is 1 only when both input bits are 1, so the constant acts as a mask that preserves some bits and clears the others. Masking and bitwise operations are covered on the and page.
The form of andi is shown below. It ANDs the value in rs1 with the constant imm and writes the result to rd.
andi rd, rs1, imm
Use it when you know in advance which bits to keep. The next line keeps the lowest 8 bits of t0 and clears the upper 24, extracting one byte from a larger value. The 0x prefix marks a hexadecimal constant.
andi t1, t0, 0xff
The constant must fit in 12 bits, so it cannot express a wide mask. For a larger mask, load it into a register with li and use and.
The RISC-V manual says the 12-bit immediate is sign-extended to 32 bits before the operation, so a negative constant has all of its upper bits set. andi, ori and xori perform the bitwise operation on register rs1 and that extended value and place the result in rd.
Two common uses follow. The first line below keeps only the lowest bit, which is 1 for odd numbers and 0 for even numbers. The second line gives the remainder after dividing by 8, because an unsigned remainder by a power of two is the lowest bits.
andi t1, t0, 1 andi t1, t0, 7
Example
andi t1, t0, 0xff # keep only the low byte
