473,603 Members | 2,635 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

signed integer overflow

REH
I asked this on c.l.c++, but they suggested you folks may be better able to
answer.

Basically, I am trying to write code to detect overflows in signed integer
math. I am trying to make it as efficient as possible without resorting to
assembly language, and without causing undefined behavior. That, of course,
means catching the overflow before it happens.

What I asked was (stripping any relevance to C++):

If the range of an integer type is not symmetrical around zero
(i.e., 2's comp.), is it safe to assume that the extra value(s) is one
the negative side?

The reason is I am currently thinking it may be easiest to do the math as
unsigned, check for overflow, and then fixup the sign. I would handle the
fact that the range may not be symmetrical around zero as a corner case.

What I learned from the folks on the C++ group:

1) C and C++ Standards are equivalent on the treatment of signed/unsigned
values. I had thought (mistakenly, I guess) that they differed slightly.

2) That the Standard (should that always be capitalized?), C++ at least,
allows only three formats: 1's comp., 2's comp., and sign/magnitude. I
didn't realize this and thought that any format was allowed, and I was
worried about my code working correctly on some weird format I've never
heard of. If that is true, then my only "corner case" is with the maximum
(in magnitude) negative value in 2's complement.

I had thought this was a problem that had been beaten to death in both
languages, but I could find nothing on the web. Well, that's not true. The
stuff I did find always assumed that signed overflow was well behaved and
worked as unsigned.

Not relevant here, but I am attempting to write a class template that
behaves like Ada's ranged types (and subtypes). That is, for example, if X
+ Y overflows or strays out of its assigned range, it will throw an
exception.

Thanks,

REH
Nov 15 '05 #1
27 4533
REH wrote:
If the range of an integer type is not symmetrical around zero
(i.e., 2's comp.), is it safe to assume that the extra value(s) is one
the negative side?
Yes. The Standard makes it clear that signed integer types are made up of a
sign bit, at least a certain number of value bits (15 for short int and
int, and 31 for long), and at least zero padding bits. Because the
representation of non-negative values of signed integer types is the same
as for unsigned integer types, it is easy to see that there can be at most
only one "extra" value, and that value must be negative because the sign
bit will have to be set in order to get the extra bit combination. Think of
(heretical!) three-bit ints, with the first of them being the sign bit:

Bit pattern Unsigned value Signed value
000 0 0
001 1 1
010 2 2
011 3 3

All remaining values must have the high bit set, and thus must be negative
in a signed type (irrespective of whether it's ones' complement, two's
complement, or sign-and-mag).
What I learned from the folks on the C++ group:

1) C and C++ Standards are equivalent on the treatment of signed/unsigned
values. I had thought (mistakenly, I guess) that they differed slightly.
No, they're equivalent TTBOMKAB.

2) That the Standard (should that always be capitalized?), C++ at least,
allows only three formats: 1's comp., 2's comp., and sign/magnitude.


It's the same for C.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
mail: rjh at above domain
Nov 15 '05 #2
REH wrote:
.... snip ...
If the range of an integer type is not symmetrical around zero
(i.e., 2's comp.), is it safe to assume that the extra value(s)
is one the negative side?

The reason is I am currently thinking it may be easiest to do the
math as unsigned, check for overflow, and then fixup the sign. I
would handle the fact that the range may not be symmetrical around
zero as a corner case.


No need to guess. For any integer type, the limiting values are
available in <limits.h>.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 15 '05 #3
Richard Heathfield wrote:
[...] Think of
(heretical!) three-bit ints, with the first of them being the sign bit:

Bit pattern Unsigned value Signed value
000 0 0
001 1 1
010 2 2
011 3 3

All remaining values must have the high bit set, and thus must be negative
in a signed type (irrespective of whether it's ones' complement, two's
complement, or sign-and-mag).


100 could be zero, which is not negative:

if (minus_zero < 0 || minus_zero > 0 || minus_zero != 0) {
puts("This isn't C!");
puts("(Or else minus zero is a trap representation, \n"
"and you're only seeing this as a consequence\n"
"of undefined behavKUHYTDjn;l kUy97609i]*&^%$");
}

Although the example is flawed, the O.P.'s supposition is
correct: If the set of values is not symmetrical about zero,
the "extra" value must be negative:

- Signed magnitude: The "extra" encoding is 10...0, which
is either "minus zero" or a trap representation. Even if
"minus zero" is allowed, its value is zero so the range
is symmetrical.

- Ones' complement: The "extra" encoding is 11...1, which
is either "minus zero" or a trap. As before, the range is
symmetrical.

- Two's complement: The "extra" encoding is 10...0, which
is either minus two-to-the-Nth or a trap. If it's a trap
the range is symmetrical; otherwise, the range is
asymmetrical and the "extra" value is negative.

That covers all the representations permitted by the Standard,
and the only case in which the range is asymmetrical has more
negative than positive values.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #4
REH

"CBFalconer " <cb********@yah oo.com> wrote in message
news:42******** ******@yahoo.co m...

No need to guess. For any integer type, the limiting values are
available in <limits.h>.

Thanks, CB, but just knowing the limits does not make it trivial to
determine whether a given arithmetic operation will overflow.

Nov 15 '05 #5
REH

"Eric Sosman" <es*****@acm-dot-org.invalid> wrote in message
news:cP******** ************@co mcast.com...
Although the example is flawed, the O.P.'s supposition is
correct: If the set of values is not symmetrical about zero,
the "extra" value must be negative:

- Signed magnitude: The "extra" encoding is 10...0, which
is either "minus zero" or a trap representation. Even if
"minus zero" is allowed, its value is zero so the range
is symmetrical.

- Ones' complement: The "extra" encoding is 11...1, which
is either "minus zero" or a trap. As before, the range is
symmetrical.

- Two's complement: The "extra" encoding is 10...0, which
is either minus two-to-the-Nth or a trap. If it's a trap
the range is symmetrical; otherwise, the range is
asymmetrical and the "extra" value is negative.

That covers all the representations permitted by the Standard,
and the only case in which the range is asymmetrical has more
negative than positive values.

Thank you Eric. Yours and Richard's posts were very helpful. Is there a
simple test to determine whether the minus zero or trap is used? Or, is
that unnecessary to know as long as the values do not overflow?

REH
Nov 15 '05 #6
Eric Sosman wrote:
Richard Heathfield wrote:

All remaining values must have the high bit set, and thus must be
negative in a signed type (irrespective of whether it's ones' complement,
two's complement, or sign-and-mag).


100 could be zero, which is not negative:


Oh, pooh.

Thank you for the correction!

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
mail: rjh at above domain
Nov 15 '05 #7
REH wrote:
"CBFalconer " <cb********@yah oo.com> wrote in message

No need to guess. For any integer type, the limiting values are
available in <limits.h>.


Thanks, CB, but just knowing the limits does not make it trivial to
determine whether a given arithmetic operation will overflow.


Yes it does. A preliminary calculation with one operand and the
limit will yield the maximum value for the other operand, so you
can avoid an overflow with a single comparison.

if (a > 0) {
if (b > 0)
if (a > (MAX_INT - b)) overflow();
}
else if (a < 0) {
if (b < 0)
if (a < (MIN_INT - b)) overflow();
}
etc.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 15 '05 #8
REH

"CBFalconer " <cb********@yah oo.com> wrote in message
news:42******** *******@yahoo.c om...
REH wrote:
"CBFalconer " <cb********@yah oo.com> wrote in message

Yes it does. A preliminary calculation with one operand and the
limit will yield the maximum value for the other operand, so you
can avoid an overflow with a single comparison.

if (a > 0) {
if (b > 0)
if (a > (MAX_INT - b)) overflow();
}
else if (a < 0) {
if (b < 0)
if (a < (MIN_INT - b)) overflow();
}
etc.


You are assuming just simple addition and subtraction. It is more complex
for other operations.

REH
Nov 15 '05 #9
REH wrote:
You are assuming just simple addition and subtraction. It is more complex
for other operations.


Indeed it is. Testing for multiplication overflow cannot really be
done efficiently in C, except for lower sized integers.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

44
8543
by: JKop | last post by:
You know how the saying goes that *unsigned* overflow is... well.. defined. That means that if you add 1 to its maximum value, then you know exactly what value it will have afterward on all implementations. But then you have signed integers. Let's say a signed integer is set to its maximum positive value. If you add 1 to it, what happens?: A) It's implementation defined what value it will
2
648
by: REH | last post by:
If the is_modulo field of the numeric_limits class is true for signed integer types, can I assume that overflow for such types is defined behavior? If so, is the behavior the same regardless of implementation? Also, if the range of an integer type is not symmetrical around zero (i.e., 2's comp.), is it safe to assume that the extra value(s) is one the negative side? Thanks,
42
6989
by: thomas.mertes | last post by:
Is it possible to use some C or compiler extension to catch integer overflow? The situation is as follows: I use C as target language for compiled Seed7 programs. For integer computions the C type 'long' is used. That way native C speed can be reached. Now I want to experiment with raising a Seed7 exception (which is emulated with setjmp(), longjmp() in C) for integer
0
7928
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8415
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8405
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8060
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6735
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5441
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3903
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2430
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1514
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.