and

and

RISC-V Assembly Reference

lyszt.net covers and and other RISC-V instructions in more detail.

Encoding format

R
31–25funct7
24–20rs2
19–15rs1
14–12funct3
11–7rd
6–0opcode
I
31–20imm[11:0]
19–15rs1
14–12funct3
11–7rd
6–0opcode
S
31–25imm[11:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:0]
6–0opcode
B
31–25imm[12,10:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:1,11]
6–0opcode
U
31–12imm[31:12]
11–7rd
6–0opcode
J
31–12imm[20,10:1,11,19:12]
11–7rd
6–0opcode

Description

and is a bitwise instruction. A register holds 32 bits, which are 32 separate 0s and 1s in a row. A bitwise instruction applies its operation to all 32 positions independently, and no carry passes between positions.

At a single bit, AND gives 1 only when both input bits are 1, and 0 otherwise. The form below applies that rule to all 32 positions, comparing rs1 and rs2 and writing the result to rd.

and rd, rs1, rs2

AND is used for masking, which keeps some bits and clears others. Where the mask has a 1, the original bit stays. Where the mask has a 0, the result is 0. ANDing a value with the mask 00001111 keeps the low four bits and clears the rest. Masking extracts one field from a value that packs several fields together.

The RISC-V manual lists and, or and xor among the register-register operations. All of them read the source registers rs1 and rs2, write the result to the destination register rd, and perform bitwise logical operations.

In the example, 0b1100 (the 0b prefix marks binary digits) is ANDed with 0b1010. Both inputs have a 1 only in the leftmost position, so the result is 0b1000, and it goes into t2.

Example

li t0, 0b1100
li t1, 0b1010
and t2, t0, t1   # t2 = 0b1000