Search code examples
syntaxvhdl

How to do a bitwise AND on integers in VHDL?


I'm learning VHDL and I'm having a problem with some code I'm trying to write to satisfy a bound-check exception.

Here is my basic summarized code:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.std_logic_arith.all;
use IEEE.NUMERIC_STD.ALL;
use ieee.std_logic_unsigned.all; 
...
port(
Address: in std_logic_vector(15 downto 0);
...
constant SIZE : integer := 4096;
variable addr: integer range 0 to SIZE-1 := 0;
...
process ... 
addr := conv_integer(Address) and (SIZE-1); --error here

The error message I get is

src/memory.vhd:37:35: no function declarations for operator "and"

Basically, my goal is to make a 16-bit address bus, reference memory with only 4096 bytes. Why do I get this odd error? Am I missing a library include or something?


Solution

  • First: Don't use std_logic_arith and numeric_std. And you don't need std_logic_arith

    You can't do bitwise ANDs on integers, so you need to do something like:

    addr := Address and to_unsigned(SIZE-1, Address'length);
    

    But you'll probably want to guarantee SIZE is a power-of-2

    what I tend to do is create a constant in bits and work up from there:

    constant mem_bits : integer := 16;
    constant SIZE     : integer := 2**16;
    

    then

    addr := Address(mem_bits-1 downto 0);