Hexadecimal to BCD Conversion

2019-09-20 12:49发布

问题:

I am trying to convert from Hex To BCD in verilog. I am not using any clocks or other stuff. In my program, I give one input at a time and convert it and show the result. But my program is giving undefined result. How can I fix it? Any solution?

module HexToBCD(num,result);

input num;

output [7:0]result;

assign result[0]=num%2;
assign num=num/2;

assign result[1]=num%2;
assign num=num/2;

assign result[2]=num%2;
assign num=num/2;

assign result[3]=num%2;
assign num=num/2;

assign result[4]=num%2;
assign num=num/2;

assign result[5]=num%2;
assign num=num/2;

assign result[6]=num%2;
assign num=num/2;

assign result[7]=num%2;
assign num=num/2;

endmodule

Regards

回答1:

I see a few unusual things with your module.

  1. num is 1 bit wide, but you are trying to divide it by 2.

  2. You are assigning to an input.

  3. You make the same assignment to num 8 times. Verilog does not work that way; all continuous assignments are evaluated in parallel.



回答2:

The following code do the conversion of a 8 bit binary number to a BCD equivalent. For explanation about the algorithm refer to this link.

module bcd (
    input [7:0] binary,
    output reg [3:0] hundreds,
    output reg [3:0] tens,
    output reg [3:0] ones);

integer i;
always @(binary) begin
    // set 100's, 10's, and 1's to zero
    hundreds = 4'd0;
    tens = 4'd0;
    ones = 4'd0;

    for (i=7; i>=0; i=i-1) begin
        // add 3 to columns >= 5
        if (hundreds >= 5)
            hundreds = hundreds + 3;
        if (tens >= 5)
            tens = tens + 3;
        if (ones >= 5)
            ones = ones + 3;

        // shift left one
        hundreds = hundreds << 1;
        hundreds[0] = tens[3];
        tens = tens << 1;
        tens[0] = ones[3];
        ones = ones << 1;
        ones[0] = binary[i];
    end
end
endmodule