close
標題:

免費註冊體驗

 

此文章來自奇摩知識+如有不便請留言告知

Bariny (two's complement)

發問:

-86 <-- negative to Binary in two's complement representation using 12 digits in the result. 我唔識點張佢change做12bit呀... thx for hepling me.... 更新: 1) 仲有..咩野係unsigned and signed integer 如果佢問What is the largest unsigned integer that can be stored in 10 bits呢? 2) 1234 in binary = 10011010010 係咪store到11bytes呢??

最佳解答:

首先說明一個 n bit 的 binary number in 2's complement 的定義。(n 大過 1) 一個 n bit 的 binary number in 2's complement 會有 n 個 bit,由左至右分別代表: 【-2^(n-1)】【2^(n-2)】【2^(n-3)】...【22】【2】【1】 就是說,由最右邊的 bit 向左會是 2^0, 2^1, 2^2, ..., 直至左邊第二個的 2^(n-2),最左邊的 bit 是 -2^(n-1)。最左邊的 bit 叫做 sign bit,因為如果這個 sign bit 是 1,這個數就是負數,相反如果 sign bit 是 0,這個數就是正數。 用 8 bit 2's complement 舉一個例子: sb ====================== 01111111=127 00000010=2 00000001=1 00000000=0 11111111=-1 11111110=-2 10000001=-127 10000000=-128 sb = sign bit 一個 n bit 的 2's complement 數字的範圍會是 -2^(n-1) 至 2^(n-1)-1。從上面的例子,一個 8 bit 的 2's complement 數字就會是 -128 至 127。 回到你的問題,-86 要轉做 12 bit 2's complement,可以這樣做: 1. 因為這是負數,所以 sign bit 要是 1,即是代表 -2^11 = -2048。 2. 計算 -2048 和 -86 的差:-86 - (-2048) = 1962 3. 將 1962 轉做二進制:11110101010 這個就是所有正數 bit 的值(當然如果長度不夠要在左邊的 bits 補上 0,只是這個例子剛好是 11 個 bits) 4. 合上 (3) 與 (1) 的結果是:111110101010 所以 -86 轉做 12 bit 2's complement 是 111110101010 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ unsigned number 是沒有 sign bit 的數字,就是說如果一個 n bit 的 binary unsigned number,就能代表 0 至 (2^n)-1 的值。由左至右分別代表: 【2^(n-1)】【2^(n-2)】【2^(n-3)】...【22】【2】【1】 相反 signed number 就代表有一個是 sign bit,就好像上面的 2's complement 就是 signed number 的一個例子,但還有其他的 signed number 例子,這裡不祥細說明。 再用 8-bit unsigned number 作例子: 用 8 bit 2's complement 舉一個例子: ====================== 01111111=127 00000010=2 00000001=1 00000000=0 11111111=255 11111110=254 10000001=129 10000000=128 要比較 n bit 的 signed number 和 unsigned number 可表達的範圍,如下: n bit 的 signed number:-2^(n-1) 至 2^(n-1)-1 n bit 的 unsigned number:0 至 (2^n)-1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1234 in binary 是 10011010010 因為這是 11 個 bit,所以如果要用 11 bit number 儲存,就只可以用 unsigned number(0 至 2047)。如果用 signed number,因為有一個是 signed bit,所以可儲存的範圍只有(-1024 至 1023)。 希望幫到你。

其他解答:
arrow
arrow
    全站熱搜

    yffuhxy 發表在 痞客邦 留言(0) 人氣()