1. Shift plus three algorithm
1. Shift the binary number one bit to the left (fill 0 in the front if it is less than 4 bits)
2. If it is moved by 8 bits, then the binary number is in the hundreds, tens and units columns, and the calculation ends
3. In any BCD In the column, if any binary number is greater than or equal to 5, add 3 to this number
4. Go back to step 1
module bin2bcd8
(
input wire [7:0] binary,
output wire [3:0] b,
output wire [3:0] c,
output wire [3:0] d
);
/*
z 作为存储 BCD 码和 二进制码的寄存器
如果输入为 8 位,那么 z 需要的长度为
0xFF = 255 ---> 10-0101-0101 +++ ????-????
总共 18 位
*/
reg [17:0] z;
always @ (*)
begin
z = 18'b0; //置 0
z[7:0] = binary; //读入低 8 位
repeat (8) //重复 8 次
begin
if(z[11:8 ]>4) //大于 4 就加 3
z[11:8 ] = z[11:8 ] + 2'b11;
if(z[15:12]>4)
z[15:12] = z[15:12] + 2'b11;
z[17:1] = z[16:0]; //左移一位
end
end
assign b = z[17:16]; //输出 BCD 码
assign c = z[15:12];
assign d = z[11:8] ;
endmodule
2. 2-4 Decoder
module decoder2_4( out, EN, in);
input EN;
input [1:0] in;
output [3:0] out;
reg [3:0] out;
always @(EN or in) begin
if (EN == 1) // 使能信号有效
case (in)
2'b00 : out = 4'b0001;
2'b01 : out = 4'b0010;
2'b10 : out = 4'b0100;
2'b11 : out = 4'b1000;
endcase
else out = 4‘b0000; // 使能信号无效
end
endmodule
Three.8421 code decoder
module decoder_8421 ( Y, en, A);
input en;
input [3:0] A;
output [9:0] Y;
reg [9:0] Y;
always @(en or A) begin
if (en == 1) // 使能信号有效
case (A)
4'b0000 : Y = 10'b0000000001;
4'b0001 : Y = 10'b0000000010;
4'b0010 : Y = 10'b0000000100;
4'b0011 : Y = 10'b0000001000;
4'b0100 : Y = 10'b0000010000;
4'b0101 : Y = 10'b0000100000;
4'b0110 : Y = 10'b0001000000;
4'b0111 : Y = 10'b0010000000;
4'b1000 : Y = 10'b0100000000;
4'b1001 : Y = 10'b1000000000;
default : Y = 10'b0000000000;
endcase
else out = 10'b0000000000; // 使能信号无效
end
endmodule
Four.8421 encoder
module Key_8421 ( Y, OUT, en, I);
input en;
input [9:0] I;
output [3:0] Y;
output OUT;
reg [9:0] Y;
reg OUT;
always @(en or I) begin
if (en == 1) // 使能信号有效,开始编码
case (I)
10'b0000000001 : {OUT, Y} = 5'b10000;
10'b0000000010 : {OUT, Y} = 5'b10001;
10'b0000000100 : {OUT, Y} = 5'b10010;
10'b0000001000 : {OUT, Y} = 5'b10011;
10'b0000010000 : {OUT, Y} = 5'b10100;
10'b0000100000 : {OUT, Y} = 5'b10101;
10'b0001000000 : {OUT, Y} = 5'b10110;
10'b0010000000 : {OUT, Y} = 5'b10111;
10'b0100000000 : {OUT, Y} = 5'b11000;
10'b1000000000 : {OUT, Y} = 5'b11001;
default : {OUT, Y} = 5‘b00000; // 使能信号有效,但输入无有效信号或有多位有效信号
endcase
else {OUT, Y} = 5‘b00000; // 使能信号无效,OUT = 0
end
endmodule
5. Four-bit binary to 8421 BCD
module _4bitBIN2bcd ( BCD1, BCD0, Bin);
input [3:0] Bin;
ouput reg [3:0] BCD1, BCD0;
always @(Bin) begin
{BCD1, BCD0} = 8'h00;
if (Bin < 10) begin
BCD1 = 4'h0;
BCD0 = Bin;
end
else begin
BCD1 = 4‘h1; // 如果Bin ≥ 10,则十位部分为1
BCD0 = Bin – 4'd10; // 各位部分等于Bin - 10
end
end
endmodule