Keywords:
$readmemb, $readmemh
Syntax:
$readmemb("<file_name>", <memory_name>");
$readmemb("<file_name>", <memory_name>, memory_start");
$readmemb("<file_name>", <memory_name>, memory_start, memory_finish");
The file_name and memory_nameare memory_start and memory_finish are optional, it missed out they default to the start index of the named memory and the end of the named memory respectively.
Memories can be stored in a file in the format shown below, the address is specified as @ <address>, where the address is in hexadecimal.
        @003
        00000011
        00000100
        00000101
        00000110
        00000111
        00001000
        00001001
        @003
        00000011
        00000100
        00000101
        @006
        00000110
        00000111
        @008
        00001000
        00001001
or if the data is contiguous, omit the address entirely.
Now that a memory file exists to access it, it has to be initialised for memory reading. This can be done by the following.
        module testmemory;
           reg [7:0] memory [9:0];
           integer   index;
           initial begin
              $readmemb("mem.dat", memory);
              for(index = 0; index < 10; index = index + 1)
              $display("memory[%d] = %b", index[4:0], memory[index]);
           end
        endmodule // testmemory
        1000_0001
        1000_0010
        0000_0000
        0000_0001
        0000_0010
        0000_0011
        0000_0100
        0000_0101
        0000_0110
        0000_0000
Store the above data in a file and run the above programme
Consider and understand the following code (run it to check):
        module fileDemo;
           integer   handle, channels, index, rand;
           reg [7:0] memory [15:0];
           initial begin
              handle = $fopen("mem.dat");
              channels = handle | 1;
              $display("Generating contents of file mem.dat");
              $fdisplay(channels, "@2");
              for(index = 0; index < 14; index = index + 1) begin
              rand = $random;
              $fdisplay(channels, "%b", rand[12:5]);
              end
              $fclose(handle);
              $readmemb("mem.dat", memory);
              $display("\nContents of memory array");
              for(index = 0; index < 16; index = index + 1)
              $displayb(memory[index]);
           end
        endmodule // fileDemo