当前位置:文档之家› 二进制转BCD码

二进制转BCD码

二进制转换成十进制 BCD码(加3移位法
底下还附带了BCD码转二进制码转化的VHDL程序
算法
"二进制数调整BCD码的方法是将二进制码左移8次,每次移位后都检查低四位LSD+3是否大于7,如是则加3,否则不加,高4位MSD作同样处理"
一、为什么左移8次
原寄存器是存二进制数的,新寄存器是存十进制数的,当然要左移8次,把数据全部移进去。

但这里要注意两件事,第一,如果只安排一个字节作十进制寄存器,原数据要小于 64H (即100)。

第二,由于新寄存器是十进制的,要随时调整。

二、检查半字节+3 是否大于 7,是,则 +3
在 51 系列里有十进制调节指令(半字节大于 9,则加 6,应该不难理解),PIC 里没有,只好采取变通的方法。

检查半字节+3 是否大于 7,也就是检查半字节是否大于 4。

因为,如果大于 4(比如5、6),下一步左移就要溢出了,所以加 3,等于左移后的加 6,起到十进制调节的作用。

那为什么要绕个圈子去检测半字节+3 是否大于 7 呢?这样程序编起来会简练一些。

一个例子
假如有一个八位二进制数255,我把他转255的十进制数
0 1111 1111 原数
1 0000 0001 ;左移一次
2 0000 0011 ; 左移二次
3 0000 0111 ;左移三次,检查低四位+3>7?
3.1 0000 1010 ;大于7,加3进行调整
4 0001 0101 ;左移四次, 检查低四位+3>7?
4.1 0001 1000 ;大于7,加3进行调整
5 0011 0001 ;左移五次
6 0110 0011 ;左移六次,检查高四位+3>7?
6.1 1001 0011 ;大于7,加3进行调整
7 1 0010 0111 ;左移七次,检查低四位+3>7?
7.1 1 0010 1010 ;大于7,加3进行调整
8 10 0101 0101 ;左移八次(得到BCD码255
Library ieee; --16位二进制转BCD码(0到9999)
Use ieee.std_logic_unsigned.all;
Use ieee.std_logic_1164.all;
Entity B_BCD is
Port ( clk,ena:in std_logic;
a: in std_logic_vector(15 downto 0);
q: out std_logic_vector(15 downto 0));
end B_BCD;
architecture behav of B_BCD is
begin
process(clk,a)
variable i: std_logic_vector(4 downto 0);
variable in_a,out_a :std_logic_vector(15 downto 0);
begin
if ena='0'then
in_a:=a; i:="00000"; out_a:="0000000000000000";
elsif clk'event and clk='1' then
if i="10000" then out_a:=out_a;
else out_a:=out_a(14 downto 0)&in_a(15);
in_a:=in_a(14 downto 0)&'0';
i:=i+1;
if i<"10000" then
if out_a( 3 downto 0)>4 then out_a( 3 downto 0):=out_a( 3 downto 0)+3;
end if;
if out_a( 7 downto 4)>4 then out_a( 7 downto 4):=out_a( 7 downto 4)+3;
end if;
if out_a(11 downto 8)>4 then out_a(11 downto 8):=out_a(11 downto 8)+3;
end if;
if out_a(15 downto 12)>4 then out_a(15 downto 12):=out_a(15 downto 12)+3;
end if;
end if;
end if;
end if ;
q<=out_a;
end process;
end behav;
以下为(0到99)BCD码转二进制码
Library ieee; --(0到99)BCD码转二进制码
Use ieee.std_logic_unsigned.all;
Use ieee.std_logic_1164.all;
Entity BCD_B is
Port ( a: in std_logic_vector(7 downto 0);
q: out std_logic_vector(7 downto 0));
end BCD_B;
architecture behav of BCD_B is
signal a1,a2,a3,a4,cq: std_logic_vector(7 downto 0);
begin
process(a)
begin
a1<="0000"&a(3 downto 0);
a2<="0000"&a(7 downto 4);
a3<=a2(6 downto 0)&'0';
a4<=a2(4 downto 0)&"000";
cq<=a4+a3+a1;
q<=cq;
end process;
end behav;。

相关主题