Carry detection

H

Hipo

Hi.
I have a question concering carry handling in C++.

When adding some value to a 32 bit Integer which causes an overflow how
is it possible to check, if a carry bit would have been set.

I know how it would word in assebmler, but I do not find a solution for C++.

thanks in advance, Hipo
 
O

osmium

Hipo said:
I have a question concering carry handling in C++.

When adding some value to a 32 bit Integer which causes an overflow how is
it possible to check, if a carry bit would have been set.

I know how it would word in assebmler, but I do not find a solution for
C++.

Alas, it is not to be. Most, if not all, high-level languages ignore integer
overflow detection. The language mavens simply throw the information out
with the garbage. You can find lots of posts on what to do about that on
Usenet. I suggest you take a look at the archives for comp.lang.c There
are no solutions that I don't consider pretty applying.
 
R

Robert Mabee

Hipo said:
When adding some value to a 32 bit Integer which causes an overflow how
is it possible to check, if a carry bit would have been set.

This is much easier in C++ than in Java since you at least have unsigned
arithmetic. If A and B are unsigned and A+B carries, then A+B < A (also
< B). Unfortunately you have to check at each step so it can get pretty
ugly.

If you have the luxury of a larger size integer then you can promote
each value to the larger size, do a bunch of work, and take the high
bits as carry when you store the low bits back to the smaller size.
 
S

Steve Pope

Robert Mabee said:
Hipo wrote:
This is much easier in C++ than in Java since you at least have
unsigned arithmetic. If A and B are unsigned and A+B carries,
then A+B < A (also
B). Unfortunately you have to check at each step so it can
get pretty ugly.

This might work:

int a, b , c;
c = a + b;
int carry_happened = 1 & ((a & b & ~c | ~a & ~b & c) >> 31);

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top