(VHDL小程序004)用VHDL设计包、库、函数(将位向量转换为整数的函数)

转自 http://www.cnblogs.com/adamite/archive/2008/08/13/1267042.html

 

 

********包格式如下:

package my_pkg is

.....................

.....................--数据类型的声明和函数的声明

.....................

end my_pkg;

package body my_pkg is  --包体名字跟包名字一样

.....................

.....................--函数定义

.....................

end my_pkg;

=========================================

*********库格式如下:

library .....

use ........

--以上为库调用

entity a is

..................

end a;

architecture a_func of a is

begin

..................

end a_func;

--以上为元件a定义

 

library ......

use .........

entity b is

..................

end b;

architecture b_func of b is

begin

....................

end b_func;

 

.........................

.........................--其他元件的定义

.........................

==================================

*********函数code例子如下:

function bit_to_int(in1:bit_vector) return integer is

alias v1:bit_vector(in1'length-1 downto 0) is in1;

variable inpv:bit_vector(in1'length-1 downto 0);

variable sum:integer:=0;

variable negative:boolean:=false;

begin

     inpv:=in1;--将要转换的数据放入一临时变量

     if(v1(v1'length-1)='1') then

          for i in v1'length-1 downto 0 loop

               inpv(i):=not inpv(i);

          end loop;

     --以上是通过最高位来判断参数位向量是否为负

     --如果是负数则转化为正数,转化为正数的过程是按位取反再加一,以上已经完成了按位取反,下面进行的再加一

     ******假设首先定义一个进位标示,初始化为1,从0到v1‘length-1循环,如果inpv(i)=1,则inpv(i)='0',并且进位标示为1,如果inpv(i)=0,则inpv(i)='1',进位表示为0,跳出循环。由此可见,可以不定义进位标示,直接进行变换。最后的exit表示跳出循环

     lp1:for i in 0 to v1'length-1 loop

          if(inpv(i)='1') then inpv(i)='0';

          else inpv(i)='1'; exit lp1;

          end if;

     end loop;

     negative :=true;--negative为负标志

     end if;

     --到此为止,将负数取反码加1得到正数

     --以下将二进制转化为正数

     for i in 0 to v1'length-1 loop

          if inpv(i)='1' then

               sum:=sum+2**i;

          end if;

     end loop;

     --以下为将二进制转化为正整数的另一种办法

     【 sum:=0;

         for i in  v1'length-1 downto 0 loop

         sum:=sum*2;

         if inpv(i)='1' then

         sum:=sum+1;

         end if;

         end loop ;】

     --如果正负标志negative为true表示为负数

     if negative then

          return(0-sum);

     else

          return(sum);

     end if;

end bit_to_int;

 

 

posted on 2009-10-21 07:49  月朗星稀  阅读(2241)  评论(0编辑  收藏  举报

导航