C++整数

Signed integers

Size/Type Range
1 byte signed -128 to 127
2 byte signed -32,768 to 32,767
4 byte signed -2,147,483,648 to 2,147,483,647
8 byte signed -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

singed integers保存数字范围如上,对于超出数字范围的数,其最终数值是截断处理。

#include <cstdint>
#include <iostream>

int main()
{
    std::int8_t a = 280;//24
    std::int8_t b = 384;//-128
    return 0;
}

int8_t是C++ 11 推出的类型,定义在头尾件<cstdint>中。

280的二进制 1 0001 1000 

384的二进制 1 1000 0000‬

另外,整数除法,其结果也是整数。如果算出来是1.6,-1.6这样的非整数,结果需去掉小数部分。结果符号同分子

#include <iostream>
 
int main()
{
    std::cout << 8 / 5;//1
    return 0;
}

Signed integers

Size/Type Range
1 byte unsigned 0 to 255
2 byte unsigned 0 to 65,535
4 byte unsigned 0 to 4,294,967,295
8 byte unsigned 0 to 18,446,744,073,709,551,615

C/C++下面unsigned,signed存储数字的个数是相同的,但是表示范围不同。unsigned数存在 wrap around 问题。以8bit整数为例,unsigned数最大255,那么他可以保存280吗?答案是可以。但是此时会出现wrap around问题,实际保存的数会是24。计算方式如下: 8bit最大数值+1为256,280/256=1...24

C++整数
#include <iostream>
 
int main()
{
    unsigned short x = 65535; // largest 16-bit unsigned value possible
    std::cout << "x was: " << x << '\n';
 
    x = 65536; // 65536 is out of our range, so we get wrap-around
    std::cout << "x is now: " << x << '\n';
 
    x = 65537; // 65537 is out of our range, so we get wrap-around
    std::cout << "x is now: " << x << '\n';
 
    return 0;
}
C++整数

除此之外,使用unsigned保存负数,实际数值都是很大的整数。这会导致while(a1-a2>0); 是个死循环(a1,a2是unsigned数)

C++整数

Fixed-width integers and size_t

在Visual Studio中,integer占用内存大小是不缺定的,这取决于你计算机(或IDE)所使用的架构。为什么就不能把表示integer的位数定死呢?简言之,早期计算机速度较慢,性能称为主要关切对象。C/C++的做法是把确定integer占用多少bit的工作交给编译器去确定,编译器来决定到底多少bit表示integer才能在目标计算机架构下呈现最大性能。对于如今计算机,硬件环境得到极大改善。这时候integer还是不确定就有点蛋疼了,这导致你代码的行为也可能是不确定的。在一种架构下运行良好的代码可能在另一种架构下就出问题了。为了保证跨平台的兼容性,C99提供了一组 fixed-width integers (定义在<stdint.h>或者<cstdint>文件中)。

 

Name Type Range Notes
std::int8_t 1 byte signed -128 to 127 Treated like a signed char on many systems. See note below.
std::uint8_t 1 byte unsigned 0 to 255 Treated like an unsigned char on many systems. See note below.
std::int16_t 2 byte signed -32,768 to 32,767  
std::uint16_t 2 byte unsigned 0 to 65,535  
std::int32_t 4 byte signed -2,147,483,648 to 2,147,483,647  
std::uint32_t 4 byte unsigned 0 to 4,294,967,295  
std::int64_t 8 byte signed -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  
std::uint64_t 8 byte unsigned 0 to 18,446,744,073,709,551,615

上一篇:Not Wool Sequences(CF-239C)


下一篇:POJ-3468 A Simple Problem with Integers