// Add 3 to digits > 4 for (j = 0; j < BCD_DIGITS; j = j + 1) begin if (bcd_reg[4*j +: 4] > 4) bcd_reg[4*j +: 4] = bcd_reg[4*j +: 4] + 3; end end
// Check and correct each BCD digit // (using blocking statements inside loop) // Digit 0 (least significant BCD digit) if (temp[3:0] > 4) temp[3:0] = temp[3:0] + 3; // Digit 1 if (temp[7:4] > 4) temp[7:4] = temp[7:4] + 3; // Digit 2 (for 3-digit BCD) if (BCD_DIGITS > 2 && temp[11:8] > 4) temp[11:8] = temp[11:8] + 3; // Add more digits if needed end
bcd = bcd_reg; end endmodule module tb_bin2bcd; reg [7:0] binary; wire [11:0] bcd; Binary To Bcd Verilog Code
for (i = 0; i < BIN_WIDTH; i = i + 1) begin // Shift left bcd_reg = bcd_reg[4*BCD_DIGITS-2:0], bin_reg[BIN_WIDTH-1]; bin_reg = bin_reg[BIN_WIDTH-2:0], 1'b0;
initial begin $monitor("Binary = %d (%b) → BCD = %b (%d %d %d)", binary, binary, bcd, bcd[11:8], bcd[7:4], bcd[3:0]); binary = 8'd0; #10; binary = 8'd5; #10; binary = 8'd42; #10; binary = 8'd99; #10; binary = 8'd170; #10; binary = 8'd255; #10; $finish; end endmodule // Add 3 to digits > 4 for
module bin2bcd #( parameter BIN_WIDTH = 8, parameter BCD_DIGITS = 3 )( input [BIN_WIDTH-1:0] bin, output [4*BCD_DIGITS-1:0] bcd ); reg [4*BCD_DIGITS-1:0] bcd_reg; reg [BIN_WIDTH-1:0] bin_reg; integer i, j;
Here’s a comprehensive write-up on , suitable for a technical blog, documentation, or academic submission. Binary to BCD Conversion in Verilog 1. Introduction In digital systems, binary numbers are the native representation, but many human‑interface devices (like 7‑segment displays, LCDs, or real‑time clocks) require Binary Coded Decimal (BCD) format. BCD represents each decimal digit of a number by a separate 4‑bit binary code. BCD represents each decimal digit of a number
bin2bcd #(.BIN_WIDTH(8), .BCD_DIGITS(3)) uut ( .bin(binary), .bcd(bcd) );
bcd = temp; end endmodule For a truly scalable version, use a generate loop or a for loop that iterates over BCD digits:
always @(*) begin bcd_reg = 0; bin_reg = bin;
module binary_to_bcd #( parameter BINARY_WIDTH = 8, // e.g., 8-bit binary input parameter BCD_DIGITS = 3 // 8-bit binary max = 255 → 3 BCD digits )( input wire [BINARY_WIDTH-1:0] binary, output reg [4*BCD_DIGITS-1:0] bcd ); integer i; reg [4*BCD_DIGITS-1:0] temp; reg [BINARY_WIDTH-1:0] bin;