2017-02-02 51 views
0

我在編寫代碼的數學和轉換過程中遇到了一些麻煩。我明白它是如何達到這個總和的,但它是如何變成負面的?將字節轉換爲int後的數學轉換

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); 
} 

這將返回:

30000 + 30000 = -5536 

一點幫助?

回答

1

30000 + 30000 = 60000,但短只能代表-32768〜32767(-2^15〜2^15 - 1)

所以,發生溢出,並返回60000 - 65536(2^16) = -5536

您必須明白,您處理的所有值實際上都是計算機內的二進制格式。

短類型用16位或2字節表示。 以二進制形式存在的30000爲0111 0101 0011 0000, 以二進制形式存在的60000爲1 1110 1010 0110 0000,只有最後16位用於表示短值。

要理解將此二進制值轉換爲十進制值,您必須具有關於https://en.wikipedia.org/wiki/Two的s_complement的一些知識,但總之它會變成-5536。 65536來自65536(2^16)的倍數以二進制形式最終具有至少16'0的事實。

+0

什麼是(2 * 16)? – momo003

+0

它只是意味着65536是2的16次方(2^16,2 ** 16等)。 –