xor

xor

RISC-V Assembly Reference

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

xor is a bitwise instruction. Like and and or, it operates on the 32 positions of a register (the and page covers bitwise operations). The name stands for exclusive OR. At each position, the result is 1 when the two input bits differ, one 0 and one 1, and 0 when they match. The form below applies this to rs1 and rs2 and writes the result to rd.

xor rd, rs1, rs2

Two properties make XOR useful. A value XORed with itself gives 0, since every bit matches itself, so the next line sets a register to zero.

xor t0, t0, t0

XOR with a mask flips the bits where the mask has a 1 and leaves the others unchanged. Flipping twice restores the original value. Simple encryption and error checks rely on this.

XOR also tests equality. After the line below, t2 is zero when the two inputs were identical and non-zero when they differ, and a branch can test the result.

xor t2, t0, t1

The RISC-V manual lists xor among the register-register operations, which read rs1 and rs2 and write the result to rd. It performs a bitwise logical exclusive OR.

The example clears t0 to 0 whatever it held before. The li instruction (load immediate) with the constant zero does the same.

Example

xor t0, t0, t0   # t0 = 0