xori

xori

RISC-V Assembly Reference

lyszt.net covers xori 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

xori performs bitwise XOR with a constant. Together with andi and ori, it rounds out the immediate logic instructions. The i means immediate: a fixed value encoded in the instruction, so a second register is unnecessary. XOR yields 1 at a bit position when the two bits differ (see the xor page). Given a constant mask, a 1 in the mask flips the corresponding bit and a 0 leaves that bit unchanged.

The syntax of xori appears below. It XORs the value in rs1 with the constant imm and writes the result to rd.

xori rd, rs1, imm

andi clears selected bits, ori sets them, and xori inverts them. Inverting twice returns the original value.

xori also provides the not instruction. Flipping all bits of a value means XOR with a mask of all 1s, and not is shorthand for the line below, because -1 in bits is all 1s. RISC-V has no dedicated instruction that inverts every bit.

xori rd, rs, -1

The RISC-V manual states that the 12-bit immediate is sign-extended to 32 bits before the operation, so the constant -1 becomes a mask of all 1s. It lists xori with the constant -1 as the bitwise logical inversion of a register, which is the not pseudo-instruction.

A common small use toggles a yes or no value held as 0 or 1. The next line switches it to the other state whenever it runs.

xori t0, t0, 1

The constant is limited to 12 bits. For wider patterns, load the mask into a register and use xor.

Example

li t0, 0
xori t1, t0, -1   # t1 = -1 (every bit flipped)