Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

1Learning Outcomes

We recommend reviewing the C Bitwise Operations before continuing.

We have previously discussed that in RISC-V, operations determine “type,” i.e., how register contents are treated (see this table). Next, we will see how this concept applies to RISC-V’s instruction set for bitwise operations.

2Bitwise Operations

As before, bitwise operations are performed on n-bit operands one bit at a time.

The RV32I ISA provides instructions for common bitwise operations.[1]. Table 6 shows that most bitwise operations correspond to two instructions:

In Table 1 below, hover over each footnote to jump to the corresponding section on this page.

Table 1:RISC-V bitwise arithmetic instructions.

Bitwise OperationRISC-V: RegisterRISC-V: Immediate
ANDand rd rs1 rs2andi rd rs1 imm
ORor rd rs1 rs2ori rd rs1 imm
XORxor rd rs1 rs2xori rd rs1 imm
NOT[2]not rd rs1 (pseudo)
Shift left[3]sll rd rs1 rs2slli rd rs1 imm
Shift right[4]srl rd rs1 rs2
sra rd rs1 rs2
srli rd rs1 imm
srai rd rs1 imm

2.1The not pseudoinstruction

In RISC-V, bitwise NOT is a pseudoinstruction and corresponds to a bitwise XOR with the immediate -1:

NOT is XOR with -1.

PseudoinstructionNameDescriptionTranslation
not rd rs1bitwise NOTR[rd] = ~(R[rs1])xori rd rs1 -1

Notes:

These three notes together explain Figure 1 below.

"TODO"

Figure 1:Add immediate instruction in RISC-V and C with negative values.

2.2Shift left

Like all RISC-V arithmetic instructions, the left-shift operation sll must write all 32 bits of the destination register. Recall our discussion of the left shift operation: the expression x << n shifts the bits of x left by n bits, filling the n lower bits with zero. The sll operation therefore fills in these new bits with 0.

2.3Shift right

Recall our discussion of the right shift operation: the expression x >> n shifts the bits of x right by n bits, filling the n lower bits with zero or one. In C, this was determined by x’s type. In RISC-V, the instruction determines what the lower bits are filled in with

shift arithmetic: signed

3Other RISC-V arithmetic instructions

General multiplication is not included in the base RISC-V ISA but is specified as part of common RISC-V extensions. See the mul instruction on the RISC-V green card.

The circuitry for general multiplication is significantly more complicated than the bitwise left- and right-shift operations discussed above. For similar reasons, we do not discuss division, modulo, and floating point operations.[5]

4Practice

Footnotes
  1. See the full set of arithmetic instructions on the RISC-V green card.

  2. We encourage you to read the RISC-V unprivileged ISA for the M Extension and the F extension.