| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
This seems to be a simple question but i would like to know ideas to make a program to calculate the largest value of integer.There is the in built function max_int,but i would like to calculate this value without using max_int.
One way is just add on 1 to integer till we get a negative value but it is time consuming,i would like some ideas to do it more easily.. I hope the great minds would help |
|
#2
|
|||||
|
|||||
|
I am not sure why you want this but a possible way could be:
c Code:
But this only works for 2's complement (and 1's complement), for details about that I have to refer you to Itsacon, he's the bit king in my opinion ;-) |
|
#3
|
|||||
|
|||||
|
Indeed we can do better
![]() Note that the following only works on 2's complement systems, but you'll be hard pressed to find anything that isn't these days :-) c Code:
Note that line 12 COULD be replaced with Code:
j = (unsigned int) i; Note that all can be done even shorter, setting j to zero and substracting 1 for example, but it's less neat (overflows and such) and if you wanted simple, you could just use MAX_INT :-)
__________________
This is my code. Is it not nifty? "The biggest problem encountered while trying to design a system that was completely foolproof, was, that people tended to underestimate the ingenuity of complete fools." ---Douglas Adams Join the Itsacon fanclub! Zero Tolerance: Spammers banned so far: 280
![]() |
|
#4
|
||||
|
||||
|
|
|
#5
|
||||
|
||||
|
Because you're using an unsigned int.
Like I said, assigning -1 to an unsigned int works, but is undefined behaviour, and MIGHT go wrong. If you want to do weird stuff, be safe, right? |
|
#6
|
||||
|
||||
|
|
|
#7
|
||||
|
||||
|
Yeah, works too, though IMHO, using sizeof is the same as using MAX_INT
otherwise you could just do pow(2, (sizeof(int) * 8)) - 1 (which is the same as pow(256, sizeof(int)) - 1.... Getting bored yet? |
|
#8
|
||||
|
||||
|
Offcourse... Simple rewrites don't count..
Besides that, pow is a _much_ more expensive operation and you'll have to include math.. |
|
#9
|
|||
|
|||
|
0111 1111
:-d i would just subtract one from unsigned int |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Calculating the maximum value of integer |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|