C++整数
Signed integers
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
C/C++下面unsigned,signed存储数字的个数是相同的,但是表示范围不同。unsigned数存在 wrap around 问题。以8bit整数为例,unsigned数最大255,那么他可以保存280吗?答案是可以。但是此时会出现wrap around问题,实际保存的数会是24。计算方式如下: 8bit最大数值+1为256,280/256=1...24 #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; } 除此之外,使用unsigned保存负数,实际数值都是很大的整数。这会导致while(a1-a2>0); 是个死循环(a1,a2是unsigned数) 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>文件中)。C++ 11 也支持这一标准。 fixed-width integers有两个弊端: ①部分平台或架构可能不支持fixed-width integers ②即使支持fixed-width integers,其性能可能没有build-in的类型好 Fast and least为了克服fixed-width integers的弊端,C++ 11有引入fixed-width integers std::int_fast#_t ? std::uint_fast#_t std::int_least#_t std::uint_least#_t 注意std::int8_t 和 std::uint8_t可能表现的行为想chars,而不是integer大多数编译器把std::int8_t?and?std::uint8_t(相应的fast,least,fixed-width)与??signed char?和?unsigned char?同样对待。这会导致std::cin?和std::cout?表现出你预料之外的结果。 #include <cstdint> #include <iostream> int main() { std::int8_t a = 280;//24 std::int8_t b = 384;//-128 return 0; } 在大多数系统上,程序输出 A,但是个别系统可能输出65. 因此,最好的方法就是避免使用?std::int8_t?and?std::uint8_t 以及相应的 fast,fixed-width。改为使用std::int16_t?or?std::uint16_t size_t#include <iostream> int main() { std::cout << sizeof(int); return 0; } 上述代码在我都环境下输出4 我们都知道sizeof会返回一个类型占据内存大小,返回值是个具体数值,这个数值的类型就是size_t。sizt_t可以理解成unsigned int,具体多少位,看具体实现。 不光sizeof返回值是size_t,其他表示类型或者对象长度的地方都会使用size_t 总结一般而言,16bit即可覆盖你想表示的数时,你大可以不必关系上面讲的问题。 如果为了性能,建议使用std::int_fast#_t 如果为了省内存,建议使用std::int_least#_t. 避免使用unsigned,8-bit fixed-width integer types,compiler-specific fixed width integers -- for example,Visual Studio defines __int8,__int16,etc… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |