Lets say i have an 8bits binary input i want to convert it t
Let\'s say i have an 8-bits binary input i want to convert it to BCD at the output , write the full Verilog code for it ,please explain it.
Solution
Verilog code for converting a 8 bit binary number into BCD format. The maximum value of a 8 bit binary number is 255 in decimal. This means we need 3 BCD digits in the output. So I have chosen the size of the output as 3 digits*4 bits = 12 bits.
module bin2bcd(
bin,
bcd
);
//input ports and their sizes
input [7:0] bin;
//output ports and, their size
output [11:0] bcd;
//Internal variables
reg [11 : 0] bcd;
reg [3:0] i;
//Always block - implement the Double Dabble algorithm
always @(bin)
begin
bcd = 0; //initialize bcd to zero.
for (i = 0; i < 8; i = i+1) //run for 8 iterations
begin
bcd = {bcd[10:0],bin[7-i]}; //concatenation
//if a hex digit of \'bcd\' is more than 4, add 3 to it.
if(i < 7 && bcd[3:0] > 4)
bcd[3:0] = bcd[3:0] + 3;
if(i < 7 && bcd[7:4] > 4)
bcd[7:4] = bcd[7:4] + 3;
if(i < 7 && bcd[11:8] > 4)
bcd[11:8] = bcd[11:8] + 3;
end
end
endmodule
Some sample inputs and the corresponding outputs are shown below:
bin = \"01100011\" , output = \"0000 1001 1001\" (99).
bin = \"11111110\" , output = \"0010 0101 0100\" (254).
bin = \"10111011\" , output = \"0001 1000 0111\" (187).
