[數據類型]
說明
在 Uno 和其他基於 ATMEGA 的板上,無符號整數(無符號整數)與整數相同,因為它們存儲 2 字節值。它們不存儲負數,但隻存儲正值,產生的有用範圍為 0 到 65,535 ((2^16) - 1)。
Due 存儲一個 4 字節(32 位)的值,範圍從 0 到 4,294,967,295 (2^32 - 1)。
無符號整數和(有符號)整數之間的區別在於解釋最高位(有時稱為"sign" 位)的方式。在 Arduino int 類型(有符號)中,如果高位是 "1",則該數字被解釋為負數,其他 15 位被解釋為(2’s complement math)。
用法
unsigned int var = val;
參數
var
: 變量的名稱。
val
:您分配給該變量的值。
示例代碼
unsigned int ledPin = 13;
注意事項和警告
當無符號變量超過其最大容量時,它們 "roll over" 回到 0,反之亦然:
unsigned int x;
x = 0;
x = x - 1; // x now contains 65535 - rolls over in neg direction
x = x + 1; // x now contains 0 - rolls over
帶有無符號變量的數學可能會產生意想不到的結果,即使您的無符號變量永遠不會翻轉。
MCU 應用以下規則:
計算是在目標變量的範圍內完成的。例如:如果目標變量是有符號的,即使兩個輸入變量都是無符號的,它也會做有符號的數學運算。
但是,對於需要中間結果的計算,代碼未指定中間結果的範圍。在這種情況下,MCU 將對中間結果進行無符號數學運算,因為兩個輸入都是無符號的!
unsigned int x = 5;
unsigned int y = 10;
int result;
result = x - y; // 5 - 10 = -5, as expected
result = (x - y) / 2; // 5 - 10 in unsigned math is 65530! 65530/2 = 32765
// solution: use signed variables, or do the calculation step by step.
result = x - y; // 5 - 10 = -5, as expected
result = result / 2; // -5/2 = -2 (only integer math, decimal places are dropped)
為什麽要使用無符號變量?
-
需要翻轉行為,例如計數器
-
帶符號的變量有點太小了,但是你想避免 long/float 的內存和速度損失。
相關用法
- Arduino unsigned char用法及代碼示例
- Arduino unsigned long用法及代碼示例
- Arduino long用法及代碼示例
- Arduino Arduino_EMBRYO_2 - setLengthXY()用法及代碼示例
- Arduino ~用法及代碼示例
- Arduino ArduinoBLE - bleDevice.advertisedServiceUuidCount()用法及代碼示例
- Arduino const用法及代碼示例
- Arduino Ethernet - server.begin()用法及代碼示例
- Arduino ArduinoBLE - BLEService()用法及代碼示例
- Arduino digitalWrite()用法及代碼示例
- Arduino ArduinoBLE - bleCharacteristic.subscribe()用法及代碼示例
- Arduino Servo - attach()用法及代碼示例
- Arduino write()用法及代碼示例
- Arduino Arduino_LSM9DS1 - readGyroscope()用法及代碼示例
- Arduino ArduinoSound - FFTAnalyzer.input()用法及代碼示例
- Arduino MKRGSM - gprs.attachGPRS()用法及代碼示例
- Arduino WiFiNINA - WiFi.config()用法及代碼示例
- Arduino MKRGSM - sms.read()用法及代碼示例
- Arduino MKRNB - getCurrentCarrier()用法及代碼示例
- Arduino Scheduler - Scheduler.startLoop()用法及代碼示例
- Arduino Arduino_LSM9DS1 - magneticFieldAvailable()用法及代碼示例
- Arduino MKRWAN - available()用法及代碼示例
- Arduino ArduinoBLE - BLE.poll()用法及代碼示例
- Arduino ArduinoBLE - bleCharacteristic.hasDescriptor()用法及代碼示例
- Arduino Ethernet - EthernetUDP.parsePacket()用法及代碼示例
注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 unsigned int。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。