当前位置:网站首页>unsigned与signed之大白话
unsigned与signed之大白话
2022-06-25 22:06:00 【彼岸的饭碗】
闲谈
有符号与无符号,顾名思义,即有负号或无负号,unsigned即可定义无符号变量,即变量不会出现小于0的值,0-1此时会从上限值往下排列,因此我们看到了许多游戏中出现的一系列bug。
为了直观的看到他们的不同,我们直接上两盘小白代码
#include "stdio.h"
#include "iostream"
#define ull signed int
using namespace std;
int main(){
int n=10;
ull p=5;
while(n>0){
n--;
p--;
cout << p << '\n';
}
return 0;
}
输出结果:
#include "stdio.h"
#include "iostream"
#define ull unsigned int //这里有所不同
using namespace std;
int main(){
int n=10;
ull p=5;
while(n>0){
n--;
p--;
cout << p << '\n';
}
return 0;
}
输出结果:
无符号整型一般是常用于各种位运算、模运算、回绕溢出利用较多的算法实现中(比如各种加密学算法、编码、压缩算法等),或者是确实对数据表示范围有要求的场合(比如必须用16bit存储上限可以达到50000的量)。
一般应用中一个变量最好用有符号数(前提是这个变量不会和别的无符号变量有直接交互),即使是一些从意义上来说不会取负数的变量,可以避免一些容易疏忽的溢出漏洞,毕竟java基本类型中不支持无符号整型不是没有道理的。
例如你要倒序遍历某个数组的时候,有符号数可以直接写成
for(int i = size-1 ; i>=0 ; --i)但如果i是个无符号数,这么写就成了一个死循环。再比如《文明》中的核弹狂魔甘地就是由于无符号数的下溢出导致的。
边栏推荐
- 流数据
- Kotlin空指针Bug
- Bi-sql stored procedure (I)
- C1. k-LCM (easy version)-Codeforces Round #708 (Div. 2)
- STL教程5-STL基本概念及String和vector使用
- Mutual conversion between QT utf8 and Unicode encoding, and the Unicode encoding output format is &xxxxx
- 如何设计产品的roadmap?
- proxy
- Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)
- 平衡二叉树AVL
猜你喜欢

如何设计产品的roadmap?

二进制、16进制、大端小端

Use of xinchida ble 5.0 Low Power Bluetooth module (at command serial port transparent transmission) rsbrs02abr

Hibernate core api/ configuration file / L1 cache details

二叉排序树

Graduation trip | recommended 5-day trip to London

使用百度地图API在地图中设置一个覆盖物(InfoWindow),可自定义窗口内容

Bi-sql stored procedure (I)

Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)

LeetCode-1528-重新排列字符串-哈希表-字符串
随机推荐
hiberate核心API/配置文件/一级缓存详解
Share a downloaded osgeo4w64 Library Based on qgis3.10
Episode 3: thread synchronization using thread lock
The software test interview has been suspended. The interviewer always says that the logical thinking is chaotic. What should I do?
关于Swoole协程容器
Use of xinchida ble 5.0 Low Power Bluetooth module (at command serial port transparent transmission) rsbrs02abr
CSDN添加页内跳转和页外指定段落跳转
Analysis on resource leakage /goroutine leakage / memory leakage /cpu full in go
CSDN add on page Jump and off page specified paragraph jump
C2. k-LCM (hard version)-Codeforces Round #708 (Div. 2)
excel如何实现中文单词自动翻译成英文?这个公式教你了
Informatics Orsay all in one 1353: expression bracket matching | Luogu p1739 expression bracket matching
Px4 multi computer simulation (gazebo)
Audio basics and PCM to WAV
php socket通信中stream_select方法的理解
为什么Integer的比较最好使用equals
Hbuilderx uses the gaude map to obtain the current location
.user.ini文件导致的php网站安装问题
MySQL InnoDB锁知识点
1.8 billion pixel Mars panorama Ultra HD released by NASA, very shocking