# ALU result is 0, how to fix this?

In system-verilog I am trying to build a small ALU unit which takes a and calculates the negative value of it (-1) in a CPU.

I wrote:

 // Secondary ALU
logic [31:0] negation_result;
always_comb
negation_result = 1'b0 - alu_a;


But the result saved in memory in hex is 00000000

I changed negation_result = 1'b0 - alu_a; to negation_result = 32'b1; and now in memory I can see 00000001

Any idea of what is causing this problem?

For example I have this ALU which works perfect:

logic [31:0] alu_result;
always_comb
case (alusel)
ALU_ADD: alu_result = alu_a + alu_b;
ALU_SUB: alu_result = alu_a - alu_b;
ALU_SLL: alu_result = alu_a << alu_b;
ALU_SLT: alu_result = (alu_as < alu_bs) ? 1 : 0;
ALU_SLTU:alu_result = (alu_a < alu_b) ? 1 : 0;
ALU_XOR: alu_result = alu_a ^ alu_b;
ALU_SRL: alu_result = alu_a >> alu_b;
ALU_SRA: alu_result = alu_a >>> alu_b;
ALU_OR : alu_result = alu_a | alu_b;
ALU_AND: alu_result = alu_a & alu_b;
default: alu_result = alu_a + alu_b;
endcase

• Try changing 1'b0 to 32'b0 to match the size of your result. – Tom Carpenter Jan 17 at 12:57
• It's cz 32'b1 is simply 1, not 1111...111 as u think. That is '1 in SV, not 32'b1. – Mitu Raj Jan 17 at 19:58
• What should you see? You never say what alu_a is. If it's 0, the logic is working correctly. – Matt Jan 17 at 22:08
• Welcome to the site. How about give us the minimum code that shows the problem. – Brian Carlton Jan 17 at 22:27
• You need to add more details on what alu_a is and what is the value you expect. – Shashank V M Jan 21 at 14:15

• Declare negation_result as signed.
• Then use negation_result = -alu_a; to negate the number.
• But inverting the bits is not the same as negation. – Elliot Alderson Jan 22 at 21:07

Negative numbers are represented in 2's complement form when you are operating on binary values. Simplest way to negate a number is: (by the definition of 2's complement):

1. take the bitwise complement of the number, i.e.: alu_result = ~alu_a
2. Add one to the result: alu_result = alu_result + 1

Check if you need to add signed in front of the logic definition.

• The tilde ~ operator is the bitwise-complement, not negation. – Elliot Alderson Jan 22 at 21:08
• @ElliotAlderson do you aware of the 2's complement concept? Negative numbers are represented with 2's complement notation, and this requires taking the bitwise-complement and adding 1 to the result. – Yunus Emre Ikiz Jan 25 at 7:12
• I am thoroughly aware of how 2's-complement works, and negating a number does not require taking the bitwise complement and adding 1...that is just one method. My comment concerns your step 1. where you say "take the bitwise negation" when in fact you are taking the bitwise complement. It is your wording that is incorrect, not the method. – Elliot Alderson Jan 25 at 12:54