無符號數

維基百科,自由的百科全書

無符號數unsigned)是計算機編程中的一種數值資料型別有符號數signed)可以表示特定類型規定範圍內的整數(包括負數),而無符號數只能表示非負數(0及正數)。

有符號數能夠表示負數的代價是能夠表示的正數範圍的縮小,因為其約一半的數值範圍要用來表示負數(如8位有符號整數中,對應8位無符號整數表示128~255的部分被用於表示-127~-1)。無符號數可以利用其所占有的所有來表示較大的數。

例如,16位有符號整數可表示 -32768~32767 之間的任意整數,而16位無符號整數可表示 0~65535 之間的數。若將有符號數轉換為二進制,則其數值類型允許的最左一位用於表示符號(1為負數,0為正數和0),但在無符號數中,最左一位與其右各位一樣用於表示數值。

大多數架構機器語言不區分有符號數及無符號數。然而算術指令通常設定進位標誌等CPU標誌,為無符號算術及溢出標誌設定。這些標誌能夠被帶入隨後的分支及算術指令中。

C語言及大部分C的派生語言為其所有有符號數類型及char類型提供了對應的無符號類型[1]。在這些語言中,若存在顯式的unsigned標識符,則將此數標識為無符號,否則為有符號(char類型除外),對應地存在signed標識符用於標識有符號數。為數值添加U後綴也可將此數值標識為無符號數。例如,在32位數中,0xFFFFFFFF表示-1,但0xFFFFFFFFU表示4294967295。

編譯器在遇到有符號數與無符號數間的比較、算術等操作時常會發出警告,因為可能因其範圍不同而導致溢出。C/C++語言規定無符號整數運算不存在溢出,如果結果超出了無符號類型能表示的最大數,則做模運算取餘數。[2]例如,對於uint32的 2-3, 其結果對0x10000模運算取餘數,最終結果為0xFFFF。

參考文獻[編輯]

  1. ^ ISO/IEC 9899:2011. International Organization for Standardization. [2020-03-08]. (原始內容存檔於2020-03-28) (英語). §6.2.5/6: For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements. 
  2. ^ ISO/IEC 9899:2011. International Organization for Standardization. [2020-03-08]. (原始內容存檔於2020-03-28) (英語). §6.2.5/9: A computation involving unsigned operands can never overflow,because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.