简体   繁体   English

unsigned long大于0xFFFFFFFF

[英]unsigned long larger than 0xFFFFFFFF

How test program can result 4294967297 if unsigned long maximum is 4294967295? 如果无符号长最大值为4294967295,测试程序如何产生4294967297?

#include <iostream>
using namespace std;
unsigned long millis_diff(unsigned long then, unsigned long now) {
    return now < then ? now + then : now - then;
}
int main()
{
    unsigned long now = 2;
    unsigned long then = 4294967295; //unsigned long maximum value
    unsigned long diff = millis_diff(then, now);
    cout << diff;
    return 0;
}

The reason is that it seems your compiler defines unsigned long int the same way as it defines unsigned long long int .:) 原因是你的编译器似乎定义了unsigned long int ,就像定义unsigned long long int 。:)

Here is a demonstrative program 这是一个示范计划

#include <iostream>
#include <limits>

int main()
{
    std::cout << "sizeof( unsigned long ) = " << sizeof( unsigned long ) << '\n';
    std::cout << "The maximum values is " << std::numeric_limits<unsigned long>::max() << '\n';
}

Its output is 它的输出是

sizeof( unsigned long ) = 8
The maximum values is 18446744073709551615

How test program can result 4294967297 if unsigned long maximum is 4294967295? 如果无符号长最大值为4294967295,测试程序如何产生4294967297?

Given the premise, it can't. 鉴于前提,它不能。

However, there is no guarantee for unsigned long maximum to be exactly 4'294'967'295, so your premise may be invalid. 但是,无法保证unsigned long最大值恰好为4'294'967'295,因此您的前提可能无效。 that maximum corresponds to the maximum that a 32 bit number can represent. 该最大值对应于32位数可以表示的最大值。 32 is the minimum required width for ( unsigned ) long , but it may be wider than that. 32是( unsignedlong最小所需宽度,但它可能比这宽。

In particular, it is typical for some 64 bit systems to have unsigned long of 64 bits, which has the maximum value of 18'446'744'073'709'551'615. 特别是,某些64位系统通常具有64位的unsigned long ,其最大值为18'446'744'073'709'551'615。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM