# Binary to BCD and BCD to Binary

## Introduction

There are several ways to convert code from one type to another. This topic will focus on code conversion from Binary Coded Decimal (BCD) to Binary and the other way around. Verilog examples on how the code can be converted is provided as well. For BCD the value 987 would be taken as each number separately: nine-eight-seven. This would result in three binary number 0b1001-0b1000-0b0111. Although, for binary the same value, 987, is represented as nine hundred and eighty seven or 0b1111011011. The conversion between these two code types will be discussed.

## BCD to Binary

Going from BCD to binary can be accomplished by multiplying each digit to its equivalent “multiplier” and adding them together. Looking at the same number, 987, as earlier - this number is nine-eight-seven in BCD although in binary it should be nine hundred and eighty seven. Thus when converting from BCD to binary, each number has a dedicated multiplier: 9 will have 100 (because it is hundreds), 8 will have 10 (because it is tens), and 7 will have 1 (becuase it is ones). Thus, the final equation for this conversion would be BINARY = 9 * 100 + 8 * 10 + 1 * 7 which equals to 987. Now, this example can be generalized as follows, BINARY = bcd3 * 1000 + bcd2 * 100 + bcd1 * 10 + bcd0 * 1. This will result in the following verilog code:

module bcd2bin
(
input wire [3:0] bcd3,
input wire [3:0] bcd2,
input wire [3:0] bcd1,
input wire [3:0] bcd0,
output wire [13:0] bin
);

assign bin = (bcd3 * 10'd1000) + (bcd2*7'd100) + (bcd1*4'd10) + bcd0;

endmodule



## Binary to BCD

Now, going from binary to BCD can be a bit more complex. In fact, the binary number being converted to BCD has to go through a series of repetitive steps. Analyzing this following code, the inputted binary number needs to go through a for loop 14 times (based on how many bits wide is the inputted signal. The following code is designed to convert a binary number up to 9999 to a BCD.

module binary2BCD(
input [13:0] binary,
output reg [3:0] thousands =0 ,
output reg [3:0] hundreds =0 ,
output reg [3:0] tens = 0,
output reg [3:0] ones = 0
);
reg [29:0]shifter=0;
integer i;
always@(binary)
begin
shifter[13:0] = binary;

for (i = 0; i< 14; i = i+1) begin
if (shifter[17:14] >= 5)
shifter[17:14] = shifter[17:14] + 3;
if (shifter[21:18] >= 5)
shifter[21:18] = shifter[21:18] + 3;
if (shifter[25:22] >= 5)
shifter[25:22] = shifter[25:22] + 3;
if (shifter[29:26] >= 5)
shifter[29:26] = shifter[29:26] + 3;
shifter = shifter  << 1;

end
thousands = shifter[29:26];
hundreds = shifter[25:22];
tens = shifter[21:18];
ones = shifter[17:14];
end
endmodule