Hexadecimal to BCD Conversion

为君一笑 提交于 2019-12-13 08:15:01

问题


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


来源:https://stackoverflow.com/questions/13841404/hexadecimal-to-bcd-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!