The reverse of 4294967295 is 5927694924, which is greater than 4294967295, which is the greatest integer which can be stored on 32 bit.
reverse number for max unsigned int
-
09-07-2023 - |
Question
I try to write a program for reverse the user input number.
The user input range is from 0 < a < 4294967295, here is EDITED code.
unsigned long int reverseNumber(unsigned long int num)
{
unsigned long int rev = 0;
while (num > 0)
{
rev = rev *10 + (num%10);
num = num/10;
}
return rev;
}
The problem is when I input 4294967295, it will output 1632727628. Why? I have no idea why it happened. How can I reverse the 4294967295.
I had changed it to unsigned long int, printf by using %lu, but still output 1632727628. Why?
Solution 2
OTHER TIPS
The reverse of 4294967295
is 5927694924
which is greater than the range of unsigned int
In your system, unsigned int
is 32-bit
wide, hence the max value that an unsigned int
can represent is 4294967295
i.e. 0xFFFFFFFF
. That is why your result is overflowing and whatever remains in 32
bits is shown as output.
If you represent 5927694924
in hex, it is 0x16151724C
which has extra 33rd
bit 1
, which is discarded and hence output is 0x6151724C
which is 1632727628
in decimal.
To print it on screen you need a greater data type like unsigned long long
or uint64_t
or unsigned long
(on 64-bit systems only), whatever your compiler supports for 64
bit integers.
The problem is when I input 4294967295, it will output 1632727628. Why?
unsigned int
can store 2^32-1
max. The reverse of 4294967295
is 5927694924
which is much bigger than 2^32-1
. Hence the out put is 1632727628
. 1632727628
is in fact 5927694924 % 4294967296
To solve this you should have used unsigned long it
. But again if the number is great than highest long it'll overflow again.