1

I am working on a VHDL implementation of the SHA-256 hash function. I have some 32-bit unsigned signals defined as such:

SIGNAL a, b : UNSIGNED (31 downto 0);

Within the specifications of the SHA-256 algorithm, it says addition must be performed modulo 2^32 in order to retain the 32-bit size in case of an overflow. Now, according to the answer to this question, it sounds like overflow is already handled with modular addition in VHDL:

There is no overflow handling, the overflow carry is simply lost. Thus the result is simply the integer result of your operation modulo 2^MAX.

I have 2 questions:

  1. In my case, MAX = 31 so does that mean that any addition operation I perform on a and b will be modded with 2^31?
  2. I need to perform addition modulo 2^32 which obviously doesn't make sense since I am working with 32-bit numbers and 2^32 is one bit too large. So is it somehow implied that I should actually be modding with 2^31?
Community
  • 1
  • 1
Ryan McClure
  • 1,183
  • 2
  • 17
  • 34

1 Answers1

4

You are fine with unsigned(31 downto 0). The 2^MAX in the post you reference is an error and should read 2^length. The length of 31 downto 0 is 32.

Think about it, 31 downto 0 can represent numbers from 0 to 2^32-1, it wouldn't make much sense if any addition of that range would be modulo 2^31 if you can represent larger numbers!

I'm not sure I understand your second question, but addition modulo 2^32 yields results in the range of 0 to 2^32-1. 2^32 is illegal, thus it's quite fine that you can't represent it with your unsigned.

QuantumRipple
  • 1,161
  • 13
  • 20
Jonathan Drolet
  • 3,318
  • 1
  • 12
  • 23
  • So VHDL would indeed take care of applying mod 2^32 to the result of the addition of the 32-bit unsigned, and I shouldn't have to explicitly perform it? – Ryan McClure Jun 03 '15 at 02:45
  • 1
    Yes, default behaviour for unsigned addition/substraction in VHDL is modulo. Non-modulo addition or overflow detection is actually harder, not much though. – Jonathan Drolet Jun 03 '15 at 02:49
  • Computer's integer arithmetic works on *residue class rings*. The computer does not calculate mod 2^32. It's just the result by discarding all bits above bit 31. Or in other words because 32 is a power of 2 -> mod 2^32 equals the lower 32 bits from bit 0 to 31 :). – Paebbels Jun 03 '15 at 19:06