0
0
VerilogHow-ToBeginner · 3 min read

How to Use readmemb in Verilog: Syntax and Example

In Verilog, readmemb is a system task used to read binary data from a text file into a memory array. You call it with the syntax $readmemb("filename", memory_array); to load the file contents into the specified array during simulation.
📐

Syntax

The $readmemb system task reads binary values from a file into a memory array in Verilog.

  • "filename": The name of the text file containing binary data.
  • memory_array: The memory variable (usually a reg array) to load data into.
  • Optional parameters can specify start and end addresses in the memory.
verilog
$readmemb("filename", memory_array, start_address, end_address);
💻

Example

This example shows how to use $readmemb to load a binary file into a memory array and display the loaded values.

verilog
module test_readmemb;
  reg [7:0] memory [0:3];
  integer i;

  initial begin
    // Load binary data from file "data.mem" into memory array
    $readmemb("data.mem", memory);

    // Display loaded memory contents
    for (i = 0; i < 4; i = i + 1) begin
      $display("memory[%0d] = %b", i, memory[i]);
    end

    $finish;
  end
endmodule

// Contents of data.mem file:
// 00000001
// 00000010
// 00000100
// 00001000
Output
memory[0] = 00000001 memory[1] = 00000010 memory[2] = 00000100 memory[3] = 00001000
⚠️

Common Pitfalls

  • File path errors: The file must be in the simulation directory or the path must be correct.
  • Data format: The file must contain binary values (0s and 1s) as text, one per line or space-separated.
  • Memory size mismatch: The memory array size must be large enough to hold all data from the file.
  • Using $readmemh instead of $readmemb for hex files is a common confusion.
verilog
$readmemb("wrong_path.mem", memory); // Wrong path causes file not found error

// Correct usage example:
$readmemb("data.mem", memory);
📊

Quick Reference

$readmemb loads binary data from a text file into a memory array during simulation.

  • File format: ASCII text with binary digits (0 or 1).
  • Memory: reg array, e.g., reg [7:0] mem [0:255];
  • Call: $readmemb("file.mem", mem);
  • Optional: specify start and end indices to load partial memory.

Key Takeaways

Use $readmemb to load binary data from a text file into a Verilog memory array during simulation.
Ensure the file contains only binary digits and is accessible in the simulation directory.
Memory array size must match or exceed the data size in the file to avoid errors.
Use correct file paths and verify file format to prevent common mistakes.
For hex data files, use $readmemh instead of $readmemb.