开发者

How to represent a number greater than the maximum value

How to represent values that exceed the max values of any particular data type (int, long ) ?

I am thinking of having another storage space acting like a counter. Once the max value is crossed, the counter updates to say , the variable has exceeded the limit for "x" number of times. Is开发者_如何学Python there some other efficient way of doing it ?

How do we display the exact value ?

P.S : Just a hypothetical question.


One way is to actually carve out one of the values for this purpose.

For example, if you have a 16-bit integral type that can represent the values from 0 through 65535 inclusive, reduce the range to 0 through 65534 and use 65535 to represent the value "too darned big".

You would have to be careful to control the operations so that they wouldn't produce that value in the normal course of events but that's reasonably easy if your language provides class capabilities.

Alternatively, you can use the next biggest data type such as long for int or long long for long and use the extra range to store information.

And, if you need more than that, you can code up a bignum library (or use one that already exists) so that there are no artificial limits placed on your numbers.


I'm not certain but I think you'll have to create your own data type (or class). This has been done before. In fact, some languages have their own implementation of this:

http://groups.csail.mit.edu/mac/users/adams/BigInt/BigInt.html


Consider an standard IEEE-754 float and the "Infinity" bit-patterns. One could reserve a similar bit-pattern inside a fixed int/long to mean "Infinity". However, the CPU won't help you out on the math/overflow states like most FPUs will.

Some languages like Ruby or elisp already "reserve" bits in integers (e.g. a fixnum in Ruby is limited to [-2^29,2^29-1] because 2 bits are used for object housekeeping). Using a specific bit-pattern vs. bit would only remove one potential value.

If you are talking about higher-level languages, say, C#, then it's easy to define a custom type:

struct IntWithStuff {
   int value;
   bool isTooBig;
}

You could also overload the various operators and implement some (explicit) casts, but I digress...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜