【归档】移位加3法实现16位二进制数到BCD码的转换

Scroll Down

CODE

module bcd(				
					input [15:0] binary,
					output reg [3:0] ten_thousands,
					output reg [3:0] thousands,
					output reg [3:0] hundreds,
					output reg [3:0] tens,
					output reg [3:0] ones
						);
	integer i;
	always@(binary)
	begin
		hundreds=4'd0; ten_thousands=4'd0;thousands=4'd0;
		tens=4'd0;
		ones=4'd0;
		for (i=15;i>=0;i=i-1)
		begin
			if(ten_thousands>=5)
				ten_thousands=ten_thousands+3;
			if(thousands>=5)
				thousands=thousands+3;
			if(hundreds>=5)
				hundreds=hundreds+3;
			if(tens>=5)
				tens=tens+3;
			if(ones>=5)
				ones=ones+3;
			ten_thousands=ten_thousands<<1;
			ten_thousands[0]=thousands[3];
			thousands=thousands<<1;
			thousands[0]=hundreds[3];
			hundreds=hundreds<<1;// '<<' is shift symbol
			hundreds[0]=tens[3];
			tens=tens<<1;
			tens[0]=ones[3];
			ones=ones<<1;
			ones[0]=binary[i];
		end
	end
endmodule


TestBench

module sim_bcd(

    );
	wire [3:0] ten_thousands,thousands,hundreds,tens,ones;
	parameter binary=16'b1111_1111_1111_1111;
	bcd uut_bcd(  .binary(binary),
							.ten_thousands(ten_thousands),
							.thousands(thousands),
							.hundreds(hundreds),
							.tens(tens),
							.ones(ones));
endmodule


测试结果

bitobcd