How to do complement for one bit in verilog

5.8k views Asked by At

I want to ask about switching one bit for example x[3] in bit vector x[0:3] to one if it's zero or to zero if it's one in verilog.So if x=0101 it will become x=0100 .I have tried concatination with not but it's error in verilog .Can you help me to do that? My code is here :http://www.edaplayground.com/x/JAc where x:input and y:x after mutate one bit

Thanks in advance.

2

There are 2 answers

0
Morgan On

To alter one bit as part of a bus:

module bit_mangle(
  input  [3:0] x,
  output [3:0] y
);

  always @* begin
    y = {x[3:1], ~x[0]} ;
  end

endmodule

I have updated a copy of your code on EDA playground, and fixed a few issues in the testharness. Working simulation on EDA Playground.

It is more common to define buses from [SIZE-1:0]. Your old Mutation code was trying to drive the input in two places rather than letting the level above drive the value.

7
Ari On
always_comb begin
   x    = 4'b0101 ; 
   x[3] = ~x[3] ; //overwrite x[3] with its complement
end

or

always_comb begin
   x    = 4'b0101 ; 
   x[3] = x[3] ^ 1'b1 ; //XOR x[3] with 1
end