-2

I am doing something in coding where it multiplies a number by from 1 to 27. I need to make a fail safe, where no number can be over this. Rounding to 2^32/2^64 would not work. It needs so be 32 bits so it can both support 32 and 64 bit OS's.

double-beep
  • 5,031
  • 17
  • 33
  • 41

2 Answers2

1

If you want to multiply 3 by 5, but know the maximum allowed result is 10, you can easily tell that 3 is too large because 3 > 10/5. That’s all there’s to it :)

Since you insist on using a 32-bit type, and I assume your programming language is C, the maximum value int32_t can represent is INT32_MAX - those two come from #include <stdint.h>.

But you may be mistaken in your assumption about being limited to 32-bit types: int64_t works on most if not all major 32-bit platforms :)

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • I used a similar code in lua: if tonumber(key) > (2^32/27-1) then print("\nInvalid key. Number too large.") GetMsgAndKey() end – マイアカウント Jan 02 '21 at 09:16
  • Basically mine checks if it the number is over the max value (2^32/27-1) and then asks for a new number if it is. – マイアカウント Jan 02 '21 at 09:19
  • The maximum value of a signed 32 bit integer is *not* 2^32! It is (2^31)-1. And the test should thus check against (((2^31)-1) / 27). Those parentheses are also important! – Kuba hasn't forgotten Monica Jan 02 '21 at 09:40
  • But lua defaults to representing all numbers as the `double` type, so you have to check what is the size of `double` on the underlying C platform that lua targets. On “big” systems like PCs, MACs, iOS and Android, a `double` is a 64-bit IEEE floating point representation and the test you propose is pointless. If the input number can be represented, then so can be the result of division by 27 (denormals may be problematic but that’s only a problem for extremely small numbers so you don’t expect to face it, I presume). – Kuba hasn't forgotten Monica Jan 02 '21 at 09:46
0

(2^32/27-1) will not give you the correct upper value. As an integer it is 159072861 which is one too low.

The maximum integer value that can be stored in 32 bits is 2^32 - 1 which works out as 4294967295.

So the maximum value is actually (2^32 - 1) // 27 which is 159072862.

Note the use of integer division which I assume is what you want.

mhawke
  • 84,695
  • 9
  • 117
  • 138