简体   繁体   中英

Detecting 32-bit dword + dword carry / C++

Assuming you have two 32-bit DWORD x and y, how can you detect if their sum would result in an overflow, but without resorting to native assembly to examine the carry flag. I'd like something with arithmetic or binary operators. I figured there might be some bit testing methods to figure it out. Thanks

Why not test the sum?

DWORD sum = x + y;
bool const overflow = (sum < x);

Should pretty much save to assume, tell me if I missed any case (this won't work in compilers adhering to C++98 or newer standards):

int overflowSum(DWORD a, DWORD b) {
     return (b > 0) ? (a + b < a) : (a + b > a);
}

If you consider your DWORD to be unsigned, you can simplify it:

int overflowSum(DWORD a, DWROD b) {
    return a + b < a;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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