 momo003 - 4 years ago 120
C# Question

# Conversion math behind byte to int

I'm having a bit of trouble wrapping my head on the math and conversion process of my code. I understand how it got to that sum but how come it turned negative?

``````static void Main(string[] args)
{
short numb1 = 30000, numb2 = 30000;
short answer = (short)Add(numb1, numb2);
Console.WriteLine("{0} + {1} = {2}", numb1, numb2, answer);
NarrowingAttempt();
Console.ReadLine();
}

static int Add(int x, int y)
{
return x + y;
}

static void NarrowingAttempt()
{
byte myByte = 0;
int myInt = 200;

myByte = (byte)myInt;
Console.WriteLine("Value of myByte: {0}", myByte);
}
``````

This returns:

``````30000 + 30000 = -5536
``````

Little help? Sangeon Park
Answer Source

30000 + 30000 = 60000, but short can only represent -32768~32767 (-2^15 ~ 2^15 - 1)

So, overflow occurs, and returns 60000 - 65536(2^16) = -5536

You must understand that all values that you handle are actually binary form inside a computer.

A short type is represented with 16 bits, or 2 bytes. 30000 in binary form is 0111 0101 0011 0000, and 60000 in binary form is 1 1110 1010 0110 0000, and only the last 16 bits are used to represent a short value.

To understand transforming this binary value into a decimal value, you must have some knowledge about https://en.wikipedia.org/wiki/Two's_complement, but in short it turns to -5536. 65536 comes from the fact that multiples of 65536 (2^16) have at least 16 '0's at the end in binary form.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download