How can I compute the range of signed and unsigned types (fwd)

Walter B. Ligon III walt at clemson.edu
Wed Apr 18 08:56:49 PDT 2001


> This is my point - how can I compute this so my code could run on any
> machine. I need to show the range possible on any machine...how can I
> compute that?
> 
> Thanks,
> Chris
> 

computing the size is rather easy - sizeof(type) gives you the number of
bytes of storage used.  As pointed out, to know the range requires knowing
the format, and that is a little trickier to figure out.  Probably the
easiest way is to compare a given value with known formats.  For example

char x = -1;

if ( (unsigned char)x == 0xfe ) printf("one's comp\n");
if ( (unsigned char)x == 0xff ) printf("two's comp\n");
if ( (unsigned char)x == 0x81 ) printf("sign/magnitude\n");

You would have to do similar tests for char, short, int, long, and long long
depending on the return value of sizeof for each type.

You can do the same thing with floating point representation, but here it is
a little trickier.  I know about IEEE and DEC formats.  There are others.
Covering your bases might not be as easy.  Getting the proper bit patterns
might be tricky also - if you have a machine you KNOW the format of you can
print a value in hex as in:

float y = 1.11;

printf("1.11 = %x\n", *(unsigned int *)&y);

outputs: 1.11 = 3f8e147b

which should be 32-bit IEEE floating point format on my Intel P3.
Once you know the format you can look up in a standard text how to compute the
min and max values for the range (and the precision for floating point 
numbers).

So, with a little research you should be able to write a quick program that
will list for you the range for the basic types on your machine, provided you
have covered all of the relevant formats.  Hopefully you can also at least
detect if the format in use is not one of the formats you have anticipated.
Though you might want to compare with several values to be a little more
sure that there isn't some weird format out that that looks the same for
some values and not others.  This is probably a bigger problem with FP formats
than anything, since the three integer formats listed above are by far the
most common (and two's comp is by far the most common of those).

Walt

-- 
Dr. Walter B. Ligon III
Associate Professor
ECE Department
Clemson University






More information about the Beowulf mailing list