- September 15th: I attended the first team meeting of the semester on Zoom, which went through semester goals and possible group assignments.
- After having my request to assist with the leads accepted by Hans, I assisted Hans and Paul with assessing the first onboarding lab for new members.
- September 22nd: I attended my first team meeting of the semester on Zoom, which went through RV32I.
- I advised the leads to add numeric first arguments to
$fatal calls and clarify always_comb’s execution at simulation start, combinational intent, and single-writer restrictions for Group A’s Onboarding Lab 2.
- September 29th: I attended my second team meeting of the semester on Zoom, which went through specifications of the modules briefly for purposes of aiding in the creation of the microarchitecture schema for Group B’s Week 3 tasks
- I designed the JAL operand and control-path diagram, including J-type immediate generation and 32-bit sign extension.
- I mapped connections to shared adders and multiplexers to calculate
PC + immJ and write PC + 4 to rd.
- I labeled bus widths and control signals, leaving final mux encodings and exception handling for shared integration
- I advised the leads to print success only after all checks pass and then call
$finish, add separate watchdog timeouts adjustable for longer tests, explicitly cast randomized data to 8 bits and control signals to 1 bit, and require positive integer WIDTH and power-of-two integer DEPTH >= 2 for Group A’s Onboarding Lab 3.
- October 6th: I attended my third team meeting of the semester on Zoom.
- October 13th: I attended my forth team meeting of the semester on Zoom.
- I registered my interest to work on top.sv (primary interest) and control_unit.sv (secondary interest) on the project repository.
- October 13th: I attended my fifth team meeting of the semester in person
- I created a when2meet to find suitable time to work with Ray and Yuhan.
- I started working on the top-level module’s testbench.
- I implemented
top.sv to connect all six core modules through the 32-bit PC, operand/writeback muxes, and branch/jump paths, with named memory and mux constants.
- I added 16,384-halfword, little-endian instruction memory with configurable image loading, missing-file diagnostics, and alignment/range guards; invalid fetches return zero without trap handling.
- I built
top_tb.sv with four 10 ns clock cycles, VCD output, and SMOKE_CYCLES + 1 preloaded NOPs. It confirms simulation completion only, without assertions or randomization; four dependencies remain unfinished.
- I enabled strict top lint and updated the Level 1 runner to reject failed commands, timeouts, and memory-image diagnostics. CI passed with Icarus 12 and Verilator 5.020: 3 passed, 0 failed, and 4 skipped.
src/top.sv
// single-cycle integration with a byte-addressed PC and halfword instruction memory
module top #(
parameter INSTR_MEM_FILE = "assembler/out/instr.mem"
) (
input logic clk
);
// fixed power-of-two halfword capacity determines the address slices
localparam int INSTR_MEM_HALFWORDS = 16384;
localparam int INSTR_INDEX_BITS = $clog2(INSTR_MEM_HALFWORDS);
// mux encodings match docs/control_table.csv
localparam logic [1:0] ALUA_RS1 = 2'd0;
localparam logic [1:0] ALUA_ZERO = 2'd1;
localparam logic [1:0] ALUA_PC = 2'd2;
localparam logic [1:0] WB_ALU = 2'd0;
localparam logic [1:0] WB_LINK = 2'd1;
localparam logic [1:0] WB_MEM = 2'd2;
// instruction memory and address paths
logic [15:0] instr_mem [0:INSTR_MEM_HALFWORDS-1];
logic [INSTR_INDEX_BITS-1:0] instr_index;
logic [31:0] instr;
logic [31:0] pc;
logic [31:0] pc_next;
logic [31:0] pc_plus4;
logic [31:0] pc_branch;
// controls use the encodings in docs/control_table.csv
logic branch_decoder_on;
logic [2:0] funct3;
logic mux_PC;
logic [1:0] mux_reg;
logic RegWrite;
logic MemWrite;
logic [1:0] mux_ALUA;
logic mux_ALUB;
logic [3:0] ALU_funct;
logic sign_val;
logic [1:0] read_size;
// register, immediate, execution, and writeback paths
logic [31:0] rs1_data;
logic [31:0] rs2_data;
logic [31:0] imm;
logic [31:0] alu_a;
logic [31:0] alu_b;
logic [31:0] alu_out;
logic zflag;
logic branch_taken;
logic [31:0] mem_data;
logic [31:0] writeback_data;
`ifndef SYNTHESIS
// simulation-only image handle
integer image_file;
`endif
// initialize PC before the first clock edge and load the image from the working directory
// assembler images are padded; sparse fixtures must provide every fetched halfword
initial begin
pc = 32'b0;
// an empty filename skips loading without clearing memory
// external simulation initialization must finish before the first clock edge
if (INSTR_MEM_FILE != "") begin
`ifndef SYNTHESIS
image_file = $fopen(INSTR_MEM_FILE, "r");
// stop simulation when the requested image cannot be opened
if (image_file == 0) begin
$fatal(1, "top: cannot open instruction image '%s'", INSTR_MEM_FILE);
end
$fclose(image_file);
`endif
$readmemh(INSTR_MEM_FILE, instr_mem, 0, INSTR_MEM_HALFWORDS-1);
end
end
// reject misaligned or out-of-range fetches before truncating the address
// zero is an invalid-fetch marker, not a NOP or a reported architectural trap
assign instr_index = pc[INSTR_INDEX_BITS:1]; // convert byte addresses to halfword indices
// aligned instructions pair an even low halfword with the next odd halfword
assign instr = (pc[31:INSTR_INDEX_BITS+1] == '0 && pc[1:0] == 2'b0)
? {instr_mem[{instr_index[INSTR_INDEX_BITS-1:1], 1'b1}], instr_mem[instr_index]}
: 32'b0;
// reuse PC plus four for sequential execution and link writeback
assign pc_plus4 = pc + 32'd4;
assign pc_branch = pc + imm;
assign pc_next = mux_PC ? (branch_taken ? pc_branch : pc_plus4) : alu_out;
// advance PC on the same rising edge as register and memory writes
always @(posedge clk) begin
pc <= pc_next;
end
// decode execution controls from the fetched instruction
control_unit u_control_unit (
.instr(instr),
.branch_decoder_on(branch_decoder_on),
.funct3(funct3),
.mux_PC(mux_PC),
.mux_reg(mux_reg),
.RegWrite(RegWrite),
.MemWrite(MemWrite),
.mux_ALUA(mux_ALUA),
.mux_ALUB(mux_ALUB),
.ALU_funct(ALU_funct),
.sign_val(sign_val),
.read_size(read_size)
);
// read both source registers and write the selected result
reg_file u_reg_file (
.rs1(instr[19:15]),
.rs2(instr[24:20]),
.rd(instr[11:7]),
.data_in(writeback_data),
.RegWrite(RegWrite),
.clk(clk),
.rs1_out(rs1_data),
.rs2_out(rs2_data)
);
// reconstruct the immediate without rescaling branch or jump offsets
instr_imm u_instr_imm (
.instr(instr),
.imm(imm)
);
// select rs1, zero for LUI, or PC for AUIPC and JAL
always_comb begin
case (mux_ALUA)
ALUA_RS1: alu_a = rs1_data;
ALUA_ZERO: alu_a = 32'b0;
ALUA_PC: alu_a = pc;
default: alu_a = 32'b0;
endcase
end
// select the second register or decoded immediate
assign alu_b = mux_ALUB ? imm : rs2_data;
// execute arithmetic and comparisons, including JALR low-bit clearing
alu u_alu (
.inA(alu_a),
.inB(alu_b),
.ALU_funct(ALU_funct),
.out(alu_out),
.zflag(zflag)
);
// combine the branch condition with ALU comparison results
branch_decoder u_branch_decoder (
.branch_decoder_on(branch_decoder_on),
.funct3(funct3),
.zflag(zflag),
.ALU_out_lsb(alu_out[0]),
.branch_decision(branch_taken)
);
// stores always use rs2, independently of the ALU operand muxes
data_mem u_data_mem (
.addr(alu_out),
.data_in(rs2_data),
.sign_val(sign_val),
.read_size(read_size),
.clk(clk),
.MemWrite(MemWrite),
.data_out(mem_data)
);
// select the ALU result, link address, or memory data
always_comb begin
case (mux_reg)
WB_ALU: writeback_data = alu_out;
WB_LINK: writeback_data = pc_plus4;
WB_MEM: writeback_data = mem_data;
default: writeback_data = 32'b0;
endcase
end
endmodule
testbench/level1_tb/top_tb.sv
// level 1 compilation and clocked simulation without functional output checks
module top_tb;
// local timing keeps the clock independent of other modules
timeunit 1ns;
timeprecision 1ps;
// one extra instruction covers the fetch after the final PC update
localparam int SMOKE_CYCLES = 4;
localparam int FIXTURE_INSTRUCTIONS = SMOKE_CYCLES + 1;
localparam logic [31:0] NOP_INSTRUCTION = 32'h00000013;
// clock stimulus and optional waveform path
logic clk;
string wave_file;
// initialize the fixture below instead of loading an external image
top #(
.INSTR_MEM_FILE("")
) dut (
.clk(clk)
);
// generate a waveform without replacing unfinished production modules
initial begin
clk = 1'b0;
// preload little-endian NOPs before the first rising edge
for (int index = 0; index < FIXTURE_INSTRUCTIONS; index++) begin
dut.instr_mem[2 * index] = NOP_INSTRUCTION[15:0]; // low halfword first
dut.instr_mem[2 * index + 1] = NOP_INSTRUCTION[31:16];
end
// accept the existing level 1 runner's waveform destination
if (!$value$plusargs("wave=%s", wave_file)) begin
wave_file = "top_tb.vcd";
end
$dumpfile(wave_file);
$dumpvars(0, top_tb);
$display("top: smoke simulation only; no functional output checks");
$display("top: unfinished dependencies may propagate unknown values");
// use the same cycle count for fixture sizing and clock stimulus
repeat (SMOKE_CYCLES) begin
#5 clk = 1'b1; // 10 ns clock period
#5 clk = 1'b0;
end
// the runner marker reports simulation completion only
$display("TEST PASSED: top compiled and completed %0d clock cycles", SMOKE_CYCLES);
$finish;
end
endmodule
- November 10th: I attended my sixth team meeting of the semester on Zoom.
- I registered my interest to work on the UART (primary interest) and the I2C (secondary interest).
- I implemented the UART peripheral with full-duplex 8N1, separate 16-byte RX/TX FIFOs, 16x timing, and an 11-bit programmable divisor (162 at 25 MHz for nominal 9600 baud). RX uses two-stage synchronization, rejects false starts and invalid stop bits, and recovers after breaks.
- I connected FPro slot 1 with status/data, divisor, TX enqueue, and explicit RX dequeue registers. Reads preserve RX data; full FIFO writes and empty dequeues are ignored.
- I added a C++ driver with rounded, clamped baud configuration, polling TX, nonblocking RX, strings, and zero-padded binary/octal/decimal/hexadecimal formatting, including safe
INT_MIN handling.
- I verified all 34 supplied UART unit checks, lint, supplemental FIFO/serial simulations, host driver sanitizer checks, and FPGA synthesis. These checks covered FIFO boundaries, serial timing, invalid frames, baud variation, and formatting edge cases.
- The supplied SoC test still fails because its monitor starts at 5,000 ns, after the first TX start at 2,780 ns. Independent waveform decoding matched the expected output, and a temporary reset-aware monitor passed; the original tests remain unchanged.
fpro/fpro_uart.sv
// UART slot 1: 8N1, LSB first, with independent RX and TX FIFOs
// word offsets: 0 reads {tx_full, rx_empty, rx_head}, 1 reads/writes dvsr,
// 2 queues wr_data[7:0], and 3 removes the RX head; other reads return zero
// reads have no side effects; writes require cs; full writes and empty pops drop
// each serial bit spans 16 ticks, with one tick per dvsr + 1 clocks
// helper modules share this assignment's required source file
// verilator lint_off DECLFILENAME
// asynchronous FIFO head, with one extra pointer bit to distinguish full
module fpro_fifo #(
parameter int W = 8,
parameter int AW = 4
)(
input logic clk,
input logic reset,
input logic wr,
input logic [W-1:0] wdata,
input logic rd,
output logic [W-1:0] rdata,
output logic empty,
output logic full
);
// storage stays unreset so synthesis can infer distributed RAM
logic [W-1:0] memory [0:(2**AW)-1];
logic [AW:0] write_ptr, read_ptr;
// the head is valid only while the FIFO is nonempty
always_comb begin
empty = write_ptr == read_ptr;
full = (write_ptr[AW] != read_ptr[AW]) &&
(write_ptr[AW-1:0] == read_ptr[AW-1:0]);
rdata = memory[read_ptr[AW-1:0]];
end
// qualify each operation against the occupancy before this clock edge
always_ff @(posedge clk) begin
// reset discards all entries without clearing storage
if (reset) begin
write_ptr <= '0;
read_ptr <= '0;
end else begin
// a full FIFO rejects a push even when a pop occurs together
if (wr && !full) begin
memory[write_ptr[AW-1:0]] <= wdata;
write_ptr <= write_ptr + 1'b1;
end
// an empty FIFO rejects a pop even when a push occurs together
if (rd && !empty) begin
read_ptr <= read_ptr + 1'b1;
end
end
end
endmodule
// sample synchronized RX at the centers of the start, data, and stop bits
module fpro_uart_rx (
input logic clk,
input logic reset,
input logic tick,
input logic rx,
output logic done,
output logic [7:0] data
);
// keep the first synchronizer stage out of the receive state machine
(* ASYNC_REG = "TRUE" *) logic rx_meta, rx_sync;
typedef enum logic [2:0] {IDLE, START, DATA, STOP, RECOVER} state_t;
state_t state;
logic [3:0] tick_count;
logic [2:0] bit_count;
// idle-high initialization avoids a false start after reset
always_ff @(posedge clk) begin
// reset both synchronizer stages together
if (reset) begin
rx_meta <= 1'b1;
rx_sync <= 1'b1;
end else begin
rx_meta <= rx;
rx_sync <= rx_meta;
end
end
// done is a single-clock pulse, independent of the tick duration
always_ff @(posedge clk) begin
// reset abandons the current frame
if (reset) begin
state <= IDLE;
tick_count <= '0;
bit_count <= '0;
data <= '0;
done <= 1'b0;
end else begin
done <= 1'b0;
// detect a start without waiting for the next baud tick
case (state)
IDLE: begin
tick_count <= '0;
bit_count <= '0;
// a low line begins start-bit qualification
if (!rx_sync) begin
state <= START;
end
end
// a short low pulse is rejected at the start-bit midpoint
START: begin
if (tick) begin
// tick 7 is the eighth tick after start detection
if (tick_count == 4'd7) begin
tick_count <= '0;
// accept only a start bit that remains low
if (rx_sync) begin
state <= IDLE;
end else begin
state <= DATA;
end
end else begin
tick_count <= tick_count + 1'b1;
end
end
end
// collect one LSB-first data bit every 16 ticks
DATA: begin
if (tick) begin
// the output is only valid when done is asserted
if (tick_count == 4'd15) begin
tick_count <= '0;
data[bit_count] <= rx_sync;
// the last data bit is followed by a stop check
if (bit_count == 3'd7) begin
state <= STOP;
end else begin
bit_count <= bit_count + 1'b1;
end
end else begin
tick_count <= tick_count + 1'b1;
end
end
end
// only a high stop bit commits the received byte
STOP: begin
if (tick) begin
// a bad frame waits for idle before accepting another start
if (tick_count == 4'd15) begin
tick_count <= '0;
done <= rx_sync;
// hold off new frames until an invalid stop returns high
if (rx_sync) begin
state <= IDLE;
end else begin
state <= RECOVER;
end
end else begin
tick_count <= tick_count + 1'b1;
end
end
end
// a sustained break must not create extra received bytes
RECOVER: begin
if (rx_sync) begin
state <= IDLE;
end
end
// restore the idle state after an invalid state encoding
default: begin
state <= IDLE;
end
endcase
end
end
endmodule
// launch on a tick boundary so every transmitted bit lasts exactly 16 ticks
module fpro_uart_tx (
input logic clk,
input logic reset,
input logic tick,
input logic start,
input logic [7:0] din,
output logic pop,
output logic tx
);
// one byte is held independently of the FIFO during transmission
typedef enum logic [1:0] {IDLE, START, DATA, STOP} state_t;
state_t state;
logic [3:0] tick_count;
logic [2:0] bit_count;
logic [7:0] shift;
// sample and remove the same FIFO head on the accepting clock edge
always_comb begin
pop = !reset && tick && start &&
((state == IDLE) || ((state == STOP) && (tick_count == 4'd15)));
end
// the registered output avoids combinational glitches on the serial pin
always_ff @(posedge clk) begin
// reset abandons the current frame and drives the line high
if (reset) begin
state <= IDLE;
tick_count <= '0;
bit_count <= '0;
shift <= '0;
tx <= 1'b1;
end else if (pop) begin
// queued frames can follow a completed stop bit immediately
shift <= din;
tick_count <= '0;
bit_count <= '0;
state <= START;
tx <= 1'b0;
end else if (tick) begin
// advance only on the shared 16x baud enable
case (state)
IDLE: begin
tx <= 1'b1;
end
// hold the start level for a full bit period
START: begin
if (tick_count == 4'd15) begin
tick_count <= '0;
state <= DATA;
tx <= shift[0]; // LSB first
end else begin
tick_count <= tick_count + 1'b1;
end
end
// shift only after the current data bit has finished
DATA: begin
if (tick_count == 4'd15) begin
tick_count <= '0;
// the eighth data bit is followed by one high stop bit
if (bit_count == 3'd7) begin
state <= STOP;
tx <= 1'b1;
end else begin
shift <= {1'b0, shift[7:1]};
bit_count <= bit_count + 1'b1;
tx <= shift[1];
end
end else begin
tick_count <= tick_count + 1'b1;
end
end
// remain idle if no queued byte is accepted at the boundary
STOP: begin
if (tick_count == 4'd15) begin
tick_count <= '0;
state <= IDLE;
end else begin
tick_count <= tick_count + 1'b1;
end
end
// restore a safe output after an invalid state encoding
default: begin
state <= IDLE;
tx <= 1'b1;
end
endcase
end
end
endmodule
// verilator lint_on DECLFILENAME
// connect the FPro registers, divider, FIFOs, and serial engines
module fpro_uart #(
parameter int CLK_HZ = 25_000_000,
parameter int BAUD = 9600,
parameter int FIFO_AW = 4
)(
input logic clk,
input logic reset,
input logic cs,
input logic read,
input logic write,
input logic [4:0] addr,
input logic [31:0] wr_data,
output logic [31:0] rd_data,
input logic rx,
output logic tx
);
// rounded reset divisor: 162 at 25 MHz and 9600 baud
localparam logic [10:0] DVSR_INIT = 11'((CLK_HZ + 8*BAUD) / (16*BAUD) - 1);
logic [10:0] dvsr, tick_count;
logic tick, set_divisor, push_tx, pop_rx;
logic [7:0] rx_byte, rx_head, tx_head;
logic rx_done, rx_empty, tx_full, tx_empty, tx_pop;
logic unused_rx_full, unused_inputs;
// only selected writes affect registers or FIFO occupancy
always_comb begin
set_divisor = cs && write && (addr == 5'd1);
push_tx = cs && write && (addr == 5'd2);
pop_rx = cs && write && (addr == 5'd3);
tick = !set_divisor && (tick_count == dvsr);
unused_inputs = &{1'b0, read, wr_data[31:11]}; // reads never change state
end
// restart the divider on writes, including when the new divisor is smaller
always_ff @(posedge clk) begin
// a divisor of zero enables every clock after reset
if (reset) begin
dvsr <= DVSR_INIT;
tick_count <= '0;
end else if (set_divisor) begin
dvsr <= wr_data[10:0];
tick_count <= '0;
end else if (tick) begin
tick_count <= '0;
end else begin
tick_count <= tick_count + 1'b1;
end
end
// completed RX frames enter the receive queue; full queues drop new bytes
fpro_fifo #(.W(8), .AW(FIFO_AW)) rx_fifo (
.clk(clk), .reset(reset), .wr(rx_done), .wdata(rx_byte),
.rd(pop_rx), .rdata(rx_head), .empty(rx_empty), .full(unused_rx_full)
);
// software pushes TX bytes and the transmitter removes them on acceptance
fpro_fifo #(.W(8), .AW(FIFO_AW)) tx_fifo (
.clk(clk), .reset(reset), .wr(push_tx), .wdata(wr_data[7:0]),
.rd(tx_pop), .rdata(tx_head), .empty(tx_empty), .full(tx_full)
);
// synchronize and decode the external receive pin
fpro_uart_rx receiver (
.clk(clk), .reset(reset), .tick(tick), .rx(rx),
.done(rx_done), .data(rx_byte)
);
// transmit independently of software reads and receive traffic
fpro_uart_tx transmitter (
.clk(clk), .reset(reset), .tick(tick), .start(!tx_empty),
.din(tx_head), .pop(tx_pop), .tx(tx)
);
// expose status and data together without removing the receive head
always_comb begin
case (addr)
5'd0: rd_data = {22'd0, tx_full, rx_empty, rx_head};
5'd1: rd_data = {21'd0, dvsr};
default: rd_data = '0;
endcase
end
endmodule
fpro/fpro_mmio_sys.sv (slot 1)
// >>> SLOT 1 UART
// connect the console to the board's USB-UART pins
fpro_uart #(.CLK_HZ(CLK_HZ), .BAUD(9600)) uart_slot1 (
.clk(clk), .reset(reset),
.cs(slot_cs[`S1_UART]), .read(mmio_rd), .write(mmio_wr),
.addr(slot_addr), .wr_data(mmio_wr_data),
.rd_data(slot_rd[`S1_UART]), .rx(uart_rx), .tx(uart_tx)
);
// <<< SLOT 1 UART
sw/fpro/uart_core.h
// UART console driver for FPro slot 1
// offset 0: RX byte, rx_empty at bit 8, tx_full at bit 9
// offset 1: 11-bit divisor, baud = clock_hz / (16 x (divisor + 1))
// offset 2: enqueue TX byte; offset 3: remove RX byte
#ifndef UART_CORE_H
#define UART_CORE_H
#include <stdint.h>
#include "fpro_map.h"
#include "fpro_io.h"
// retain the slot address without runtime initialization
class UartCore {
public:
// register offsets and status fields
enum { REG_RD = 0, REG_DVSR = 1, REG_WR = 2, REG_RM = 3 };
enum { MASK_DATA = 0xFF, MASK_RX_EMPTY = 0x100, MASK_TX_FULL = 0x200 };
constexpr explicit UartCore(uint32_t base) : base_(base) {}
// round to the nearest tick period and clamp to the 11-bit divisor range
void set_baud_rate(uint32_t baud) {
// a zero baud request preserves the current setting
if (baud == 0) return;
// dividing first preserves rounding without overflowing at large baud
const uint32_t bit_clocks = (SYS_CLK_FREQ * 1000000u) / baud;
uint32_t ticks = (bit_clocks >> 4) + ((bit_clocks & 15u) >= 8u);
// saturate unsupported rates instead of wrapping the divisor
if (ticks == 0) ticks = 1;
if (ticks > 2048u) ticks = 2048u;
io_write(base_, REG_DVSR, ticks - 1u);
}
// read the current TX FIFO status
bool tx_full() const {
return (io_read(base_, REG_RD) & MASK_TX_FULL) != 0;
}
// read the current RX FIFO status
bool rx_empty() const {
return (io_read(base_, REG_RD) & MASK_RX_EMPTY) != 0;
}
// wait for FIFO space before sending one byte
void tx_byte(uint8_t b) {
// volatile MMIO reads observe the transmitter draining the FIFO
while (tx_full()) {}
io_write(base_, REG_WR, b);
}
// read status and data once, then remove only a valid RX byte
int rx_byte() {
const uint32_t status = io_read(base_, REG_RD);
// an empty FIFO is not modified
if ((status & MASK_RX_EMPTY) != 0) return -1;
io_write(base_, REG_RM, 0);
return static_cast<int>(status & MASK_DATA);
}
// preserve every character bit, including values above 127
void disp(char ch) {
tx_byte(static_cast<uint8_t>(ch));
}
// send a zero-terminated string; a null pointer produces no output
void disp(const char *s) {
// reject a missing string before dereferencing it
if (s == nullptr) return;
// use byte writes without newline translation
while (*s != '\0') tx_byte(static_cast<uint8_t>(*s++));
}
// decimal output without padding
void disp(int n) {
disp(n, 10, 0);
}
// print decimal magnitude or unsigned bits in base 2, 8 or 16
// len counts digits only; padding follows an optional minus sign
void disp(int n, int base, int len) {
// reject unsupported bases before division
if (base != 2 && base != 8 && base != 10 && base != 16) return;
uint32_t value = static_cast<uint32_t>(n);
// unsigned negation also handles the most negative int
if (base == 10 && n < 0) {
tx_byte('-');
value = 0u - value;
}
// collect at most 32 binary digits, including one digit for zero
char digits[32];
int used = 0;
const uint32_t shift = base == 2 ? 1u : base == 8 ? 3u : 4u;
const uint32_t mask = static_cast<uint32_t>(base - 1);
// extract digits without general division for power-of-two bases
do {
uint32_t digit;
// halve the remainder calculation to avoid a second division helper
if (base == 10) {
const uint32_t quotient = value / 10u;
digit = ((value >> 1) - 5u * quotient) * 2u + (value & 1u); // restore parity
value = quotient;
} else {
// binary, octal and hexadecimal take low bits directly
digit = value & mask;
value >>= shift;
}
// store least-significant digits first with uppercase hex letters
digits[used++] = static_cast<char>(digit < 10u ? '0' + digit : 'A' + digit - 10u);
} while (value != 0);
// stream padding separately so len cannot overrun the digit buffer
while (len > used) {
tx_byte('0');
--len;
}
// send the stored digits in their display order
while (used != 0) tx_byte(static_cast<uint8_t>(digits[--used]));
}
private:
// byte address of the UART slot
uint32_t base_;
};
#endif