sb

sb

RISC-V Assembly Reference

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

sb writes one byte (8 bits) to memory, which is the smallest amount a store can write. It is the store equivalent of the lb and lbu loads. The syntax appears below. It reads the value in source register rs2 and writes its lowest 8 bits to the address formed by base register rs1 plus the offset. The operand layout matches sw, with the source register listed first.

sb rs2, offset(rs1)

Only the lowest 8 of the register's 32 bits reach memory and the remaining bits are discarded. A store has no signed or unsigned form, since it narrows the value and keeps the low byte. A value wider than a byte loses its extra bits with no warning. Storing 300 writes 44, because 300 wraps past 256.

Memory's smallest unit is a byte, so sb builds data one byte at a time, for tasks such as assembling text character by character, filling a buffer or writing individual color values. Consecutive bytes occupy addresses one apart, so a loop advances by adding 1.

The RISC-V manual states that sb stores the low 8 bits of register rs2 to memory at the address of rs1 plus the sign-extended 12-bit offset. Memory is byte-addressed, so a byte store is always naturally aligned.

A common exercise writes text by hand. Store the code of each character with sb, end the sequence with a 0 byte, then print it. The codes 72, 105 and 0 in memory print as the word Hi, which shows that a string is bytes in consecutive memory slots terminated by a zero. A store changes only the one targeted byte and the bytes beside it keep their previous values.

Example

la t0, slot
li t1, 200
sb t1, 0(t0)   # memory at slot now holds the low 8 bits, 200