[数据类型]
说明
在 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
