Search code examples
logicbit-manipulationverilogbitset

Bitset at the logic-gate level


I'm looking into implementing a 4-bit BitSet function at the logic gate level so that it can be written in structural Verilog--I have looked elsewhere for an answer to this question, but can only find C/C++ resources, which operate at a higher level and are mostly unehlpful to me.

The inputs to my interface are a 4-bit number x, a two-bit number index, containing the index to be set or cleared in x, a one-bit number value, containing the value x[index] should be set to (1 or 0 to set or clear, respectively), and a 4-bit output y, which is the final outcome of x.

To my understanding, setting a value in x follows the logic y |= 1 < < x and clearing a value in x follows y &= 1 < < x, such that if value is equal to 1, sending it through an OR gate with the value already in that index of x will result in a 1, and if value is equal to 0, sending it through an AND gate with the value already in that index of x will result in a 0. This makes sense to me.

It also makes sense that if I am starting with a 4-bit number x, that I might put it through a 1-to-4 DEMUX block (aside from the basic logic gates, I have MUX, DEMUX, magnitude comparators, and binary adders at my disposal) to obtain the individual bits.

What I am unsure about is how to get from the four separate bits to selecting one of them to modify based on the value stored in index using only basic logic gates. Any ideas or pointers for me to start from? Am I thinking about this the right way?


Solution

  • I think you are looking for something like this

    reg [3:0] x;
    reg [3:0] y;
    reg [1:0] index;
    
    // wont work in synthesis
    x[index] = 0;
    

    In Verilog you can access each bit individually using [Bit_Number] But in your case the index is not constant which will end up failing during synthesis. What you can do is write an if else to check the index and change the right index so

    if (index == 1) // change bit one
        x[1] = 1'b0; // value to assign is zero here
    else if(index == 2)
        x[2] 1'b0;
    

    A side note:

    You can also assign values

    // Here x gets the bit 1 and bit 0 of y concatenated with the value of index 
    x = {y[1:0],index};
    

    So assume

    y = 4'b1011;
    index = 2'b00;
    x =  {y[1:0],index} = 1100