Wednesday, May 21, 2008

Number Flip in numeric data types

Look at the code below. It prints -128 as output. Oops!!! How?

using System;

namespace NumberFlipDemo
{
class Program
{
static void Main(string[] args)
{
sbyte i = 127;
i++;
Console.WriteLine(i.ToString());
}
}
}
Let dig out the answer.
If we look at carefully, signed byte has range from -128 to 127.
Three methods to represent negative numbers:
Signed Magnitude -->Two representations for 0; -1 repsentated as 81.
1's Complement --> Two Representation for 0; -1 represented as FE.
2'Complement --> Single Representation for 0; -1 represented as FF.
How negative numbers are represented in the machine? Let's check.See the code here.

static void Main(string[] args)
{
sbyte i = -1;
Console.WriteLine(i.ToString("x"));
//parameter "x" to ToString gives hex o/p.
}

Output is FF. Machine uses 2's complement.

How to compute 2's Complement representation?Consider we want to represent -2 in 2's complement.
Take binary representation of 2 i.e. 0000 0010. Complement all bits. Result is 1111 1101. Now add 1 to it. We will get 1111 1110 i.e. FE.

To compute 2's complement representation of a number. First complement the bits of binary representation of the number absolute.( abs(-2)=2). Add bit 1 to the complemented bits. The result is 2's complement.
Now back to our question. Why the above code snippet gives wrong o/p without any error?
Consider that size of integer is 2 bits. Hence range of numbers to be accomodated in integer data type is -2 to 1. Let put binary representation of all these numbers in a table.

1--> 01
0--> 00
-1 --> 11 (2's complement)
-2 --> 10 (2's complement)


Now if my integer variable has a extreme positive value i.e. 1 e.g. i=1;
Add 1 to i.

i+1=1+1 =>(01)+(01)=(10)=> -2
i has value 1 i.e. binary 01. Add 1 bit to it.See the result. It gives us 10 which is being binary representation for -2.

In same fashion, number flips to -128 in case of signed byte. The theory is applicable to all whole number data types i.e. byte, sbyte,int, short, long.


Be careful while making choice of data type!!! The theory applies to all programming lanaguages.
Post a Comment