In C++, how do I pass a 32 bit number into an 'int' variable without anything above 0x7FFFFFFF being considered negative?

1

I need to have an int variable go up to 4294967295 (0xFFFFFFFF), without using unsigned and long, so it can actually be used by other functions. Is that even possible?

c++
asked on Stack Overflow Nov 4, 2020 by Maxim Khannaov • edited Nov 4, 2020 by Jonathon Reinhart

2 Answers

3

You can't, unless you find a platform with an int that's larger than 32 bits (they are at the time of writing rare).

If you need to use a signed type, then std::int64_t is a good choice. Or long long is also guaranteed to be large enough.


If you're absolutely constrained by the interface to your function then you could break your number up into two parts - and adopt the convention that you need to call the function twice to get anything meaningful out of it. But that could make your program very brittle.


Another option: if your function is allowed to take the int by reference then you could have an array of two ints at the call site, and pass the first one to your function. You can then reach the other using pointer arithmetic within the function body! Again, this will make your code brittle but it would work.

answered on Stack Overflow Nov 4, 2020 by Bathsheba • edited Nov 4, 2020 by Bathsheba
3

You can't. Because: an int value is defined as 31 bits plus one leading bit as a sign.

You can push whatever you want into the 32 bits of an int, as long as it is declared as int, the leading bit will always be interpreted as the sign.

answered on Stack Overflow Nov 4, 2020 by Gyro Gearloose • edited Nov 4, 2020 by Bathsheba

User contributions licensed under CC BY-SA 3.0