2.3 Integer overflow
Getting maximum number of someword
Maximum unsigned number is just a number where all bits are set: 0xFF....FF(this is -1 if thewordis
treated as signed integer). So you take aword, set all bits and get the value:
#include <stdio.h>
int main()
{
unsigned int val=~0; // change to "unsigned char" to get maximal value for the unsigned⤦
Ç 8-bit byte
// 0-1 will also work, or just -1
printf ("%u\n", val); // %u for unsigned
};
This is 4294967295 for 32-bit integer.
Getting minimum number for some signedword
Minimum signed number is encoded as0x80....00, i.e., most significant bit is set, while others are cleared.
Maximum signed number is encoded in the same way, but all bits are inverted:0x7F....FF.
Let’s shift a lone bit left until it disappears:
#include <stdio.h>
int main()
{
signed int val=1; // change to "signed char" to find values for signed byte
while (val!=0)
{
printf ("%d %d\n", val, ~val);
val=val<<1;
};
};
Output is:
...
536870912 -536870913
1073741824 -1073741825
-2147483648 2147483647
Two last numbers are minimum and maximum signed 32-bitintrespectively.
2.3 Integer overflow
I intentionally put this section after the section about signed number representation.
First, take a look at this implementation ofitoa()function from [Brian W. Kernighan, Dennis M. Ritchie,The
C Programming Language, 2ed, (1988)]:
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) / record sign /
n = -n; / make n positive /
i = 0;
do { / generate digits in reverse order /
s[i++] = n % 10 + '0'; / get next digit /
} while ((n /= 10) > 0); / delete it /
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
strrev(s);