473,785 Members | 2,498 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Signed int -0 ?

A signed int reserves one bit to signify whether a number is positive or
negative. In light of this, a colleague asked me whether there existed an
int in C++ that was -0, a zero with the negative bit set. I was intrigued
by this, so I tried the following code:

#include <stdio.h>

int main(int, char**) {
int a(-0);
printf("a=%d\n" , a);
if ( a==0 ) printf("a==0\n" );
if ( a==-0 ) printf("a==-0\n");
return 0;
}

The output is:

a=0
a==0
a==-0

So it seems that no such number can be used in C++, and speaking of
mathematical numbers, it makes perfect sense, but what is actually going on
"behing the curtains" in C++ since the compiled code can't discern between
+0 and -0 ?

--
Christian Stigen Larsen -- http://sublevel3.org/~csl/
Jul 19 '05 #1
20 7560
On Thu, 3 Jul 2003 13:38:13 +0000 (UTC), cs******@newsca che.ntnu.no
(Christian Stigen Larsen) wrote:
A signed int reserves one bit to signify whether a number is positive or
negative. In light of this, a colleague asked me whether there existed an
int in C++ that was -0, a zero with the negative bit set. I was intrigued
by this, so I tried the following code:

#include <stdio.h>

int main(int, char**) {
int a(-0);
printf("a=%d\n" , a);
if ( a==0 ) printf("a==0\n" );
if ( a==-0 ) printf("a==-0\n");
return 0;
}

The output is:

a=0
a==0
a==-0

So it seems that no such number can be used in C++, and speaking of
mathematical numbers, it makes perfect sense, but what is actually going on
"behing the curtains" in C++ since the compiled code can't discern between
+0 and -0 ?


Search for "two's complement" and you'll see. It's not just as simple as
reserving a bit for the sign.

--
Be seeing you.
Jul 19 '05 #2
Christian Stigen Larsen wrote:
A signed int reserves one bit to signify whether a number is positive
or
negative. In light of this, a colleague asked me whether there
existed an
int in C++ that was -0, a zero with the negative bit set. I was
intrigued by this, so I tried the following code:

#include <stdio.h>

int main(int, char**) {
int a(-0);
printf("a=%d\n" , a);
if ( a==0 ) printf("a==0\n" );
if ( a==-0 ) printf("a==-0\n");
return 0;
}

The output is:

a=0
a==0
a==-0

So it seems that no such number can be used in C++, and speaking of
mathematical numbers, it makes perfect sense, but what is actually
going on "behing the curtains" in C++ since the compiled code can't
discern between +0 and -0 ?


Negative numbers are usually expressed as 2's complement, where e.g. an
8 bit number can represent values from -128 to +127, including onle one
possible value for 0. It's not just one sign bit that is different.

Btw: Somehow, but not totally unrelated, in floating point units, there
actually often is +0 and -0, so while e.g. 1-1 is 0, I think -1+1
results in -0. This can be useful in some calculations.

Jul 19 '05 #3

"Christian Stigen Larsen" <cs******@newsc ache.ntnu.no> wrote in message news:sl******** *************@g aupe.stud.ntnu. no...
A signed int reserves one bit to signify whether a number is positive or
negative. In light of this, a colleague asked me whether there existed an
int in C++ that was -0, a zero with the negative bit set. I was intrigued
by this, so I tried the following code:

There are several singed integer representations that are possible. While
the positive numbers are all pretty straight forward binary (this is required
by the standard), the negatives can be handled in a number of ways.
Some of thse have the possiblity for a negative zero value. However, the
most common representation used today is called "two's complement".
Two's complement has no negative zero, but it does have one more
negative value available than positive. That is, an 8 bit twos complement
number goes from -128 to 127.
Jul 19 '05 #4
"Rolf Magnus" <ra******@t-online.de> wrote...
Christian Stigen Larsen wrote:
A signed int reserves one bit to signify whether a number is positive
or
negative. In light of this, a colleague asked me whether there
existed an
int in C++ that was -0, a zero with the negative bit set. I was
intrigued by this, so I tried the following code:

#include <stdio.h>

int main(int, char**) {
int a(-0);
printf("a=%d\n" , a);
if ( a==0 ) printf("a==0\n" );
if ( a==-0 ) printf("a==-0\n");
return 0;
}

The output is:

a=0
a==0
a==-0

So it seems that no such number can be used in C++, and speaking of
mathematical numbers, it makes perfect sense, but what is actually
going on "behing the curtains" in C++ since the compiled code can't
discern between +0 and -0 ?


Negative numbers are usually expressed as 2's complement, where e.g. an
8 bit number can represent values from -128 to +127, including onle one
possible value for 0. It's not just one sign bit that is different.


Both signed magnitude representation and 1's complement (which are,
IIRC, also allowed) have -0.

Victor
Jul 19 '05 #5
On Thu, 3 Jul 2003 13:38:13 +0000 (UTC), cs******@newsca che.ntnu.no
(Christian Stigen Larsen) wrote:
A signed int reserves one bit to signify whether a number is positive or
negative.
On the contrary, it doesn't do that for the most common
representation, 2s complement.

In light of this, a colleague asked me whether there existed anint in C++ that was -0, a zero with the negative bit set. I was intrigued
by this, so I tried the following code:

#include <stdio.h>

int main(int, char**) {
int a(-0);
printf("a=%d\n" , a);
if ( a==0 ) printf("a==0\n" );
if ( a==-0 ) printf("a==-0\n");
return 0;
}

The output is:

a=0
a==0
a==-0
That is the required output, regardless of the integer representation
used. (0 == -0 must be true).

So it seems that no such number can be used in C++, and speaking of
mathematical numbers, it makes perfect sense, but what is actually going on
"behing the curtains" in C++ since the compiled code can't discern between
+0 and -0 ?


Read up on 2s complement. Even in a 1s complement implementation, the
for an 8-bit binary number the bit pattern 11111111 will compare equal
to 00000000, since 11111111 and 00000000 are both representations of
0. For sign magnitude representations , 10000000 == 000000000 will hold
true for the same reason.

Tom
Jul 19 '05 #6
It all comes down to how the computer represents those negative numbers. It
does not exactly just reserve one bit as you say:

decimal binary (8-bit)
-3 11111101
-2 11111110
-1 11111111
0 00000000
1 00000001
2 00000010
3 00000011

Thus you can see why there can be no -0. With each increase, the number
increases by one. For further explanation, to convert a number to a
negative, all you do is reverse all the bits (take the one's complement) and
then add one (take the two's complement). Thus:

If we start with 0: 00000000
Take the one's complement: 11111111
Take the two's complement: 00000000 (drop the 1 off from the end)

You see we get the same number. Thus, no -0 exists.

-- MiniDisc_2k2
To reply, replace nospam.com with cox dot net.

"Christian Stigen Larsen" <cs******@newsc ache.ntnu.no> wrote in message
news:sl******** *************@g aupe.stud.ntnu. no...
A signed int reserves one bit to signify whether a number is positive or
negative. In light of this, a colleague asked me whether there existed an
int in C++ that was -0, a zero with the negative bit set. I was intrigued
by this, so I tried the following code:

#include <stdio.h>

int main(int, char**) {
int a(-0);
printf("a=%d\n" , a);
if ( a==0 ) printf("a==0\n" );
if ( a==-0 ) printf("a==-0\n");
return 0;
}

The output is:

a=0
a==0
a==-0

So it seems that no such number can be used in C++, and speaking of
mathematical numbers, it makes perfect sense, but what is actually going on "behing the curtains" in C++ since the compiled code can't discern between
+0 and -0 ?

--
Christian Stigen Larsen -- http://sublevel3.org/~csl/

Jul 19 '05 #7
Victor Bazarov wrote:
Negative numbers are usually expressed as 2's complement, where e.g.
an 8 bit number can represent values from -128 to +127, including
onle one possible value for 0. It's not just one sign bit that is
different.


Both signed magnitude representation and 1's complement (which are,
IIRC, also allowed) have -0.


That's why I used the word "usually" instead of "always".

Jul 19 '05 #8
For readers who skim, I'll start with a question (instead of burying it
below):
*** Is there a C++ library function that prints binary representations
of numbers?

Continuing. Thanks for the explanations. I was wondering yesterday
whether -0 had a different bit representation from 0. I thought how
terrible it would be if -0 *did* have a different bit representation
from 0, and NULL were defined as -0, and someone wrote an if-test that
relied on NULL being 0.

e.g.,
#define NULL -0 // redefine the NULL macro
....
char* buf = (char*)malloc(s izeof(char)*N);
if (!buf) { // if NULL has a nonzero bit representation, this will fail!
exit(1);
}

I think we should rely on bit representations of things only when we
have to (e.g., low-level file processing) or when we're trying to make
programs run more efficiently (e.g., bit ops). And I stop here because I
haven't done much of either of these.

Below is a little program I wrote to print binary representations . Yeah,
most of us have probably written one of these. If a C++ library function
exists for this, I feel silly.

I thought that actually *printing* bit representations was necessary to
show that the bit representations of -0 and 0 differ, because C++ can do
typecasts behind your back (e.g., from -0 to 0? I didn't know and didn't
want to take a chance).

--Suzanne
------------------------------------------------------------------------------------
// File: BitRepresentati onsMain.cpp

#include <iostream>

///////////////////////////////////////////////////////////////////////////////
// TYPEDEFS AND CONSTANTS
///////////////////////////////////////////////////////////////////////////////

const int NUM_BITS_PER_CH AR = 8;

///////////////////////////////////////////////////////////////////////////////
// UTILITY FUNCTIONS
///////////////////////////////////////////////////////////////////////////////

// Convert integer n to a null-terminated string of 0's and 1's
representing its
// binary representation.
template<class T>
char* toBinary(char* binary, T n)
{
// Advance the pointer all the way to the right.
long nbits = sizeof(T) * NUM_BITS_PER_CH AR;
binary += nbits;

// Append null.
*binary = '\0';
binary--;

// Write chars via the pointer.
for (int i=0; i < nbits; i++)
{
*binary = (n & 1)==1 ? '1' : '0';
n = n >> 1;
binary--;
}
binary++;
return binary;
}

///////////////////////////////////////////////////////////////////////////////
// MAIN
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
char* binary = (char*)malloc(s izeof(long) * NUM_BITS_PER_CH AR + 1);

std::cout << "-0:\t" << toBinary<int>(b inary, int(-0)) << "\n";
std::cout << "0:\t" << toBinary<int>(b inary, int(0)) << "\n";
std::cout << "-0:\t" << toBinary<long>( binary, long(-0)) << "\n";
std::cout << "0:\t" << toBinary<long>( binary, long(0)) << "\n";
std::cout << "-0:\t" << toBinary<char>( binary, char(-0)) << "\n";
std::cout << "0:\t" << toBinary<char>( binary, char(0)) << "\n";

for (int i=-3; i<=3; i++)
{
std::cout << i << ":\t" << toBinary<int>(b inary, int(i)) << "\n";
}

free(binary);

return EXIT_SUCCESS;
}

MiniDisc_2k2 wrote:
It all comes down to how the computer represents those negative numbers. It
does not exactly just reserve one bit as you say:


Jul 19 '05 #9
Thanks for the feedback.
(e.g., from -0 to 0?

Why do you think that would be a type conversion? Anyway, the compiler
may keep the bits as they are and just treat 0 and -0 as equal.


*Suppose* (this is hypothetical) there were different representations of
0 and -0 for longs but not for ints.

Consider the following (made-up example):

if (0 == -0)... // possibly convert one of these

To compare 0 and -0, they must have the same type. So in *this* made-up
case, -0 would be a long and 0 would be an int, so 0 would be converted
(converted, not cast) to a long.

Similarly to the following (real example):

if (float(0.0) == double(0.0))... // convert float(0.0) to a double

** Is this not right?
const int NUM_BITS_PER_CH AR = 8;

Better use std::numeric_li mits<char>::dig its from the <limits> header or
CHAR_BIT from <climits>.

Good idea.

** Doesn't that just give the number of base-10 digits? If so, I guess I
could take the log base-2 of that to get the number of base-2 digits.

Suzanne

Jul 19 '05 #10

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

Similar topics

19
6482
by: MiniDisc_2k2 | last post by:
Okay, here's a question about the standard. What does it say about unsigned/signed mismatches in a comparison statement: char a = 3; unsigned char b = 255; if (a<b) Now what's the real answer here? If a is converted to unsigned, then b>a. But, if b is converted to signed,then a>b. What's the correct coversion (what is the compiler supposed to do?)
8
2247
by: Rade | last post by:
Following a discussion on another thread here... I have tried to understand what is actually standardized in C++ regarding the representing of integers (signed and unsigned) and their conversions. The reference should be 3.9.1 (Fundamental types), and 4.7 (Integral conversions). It seems to me that the Standard doesn't specify: 1) The "value representation" of any of these types, except that (3.9.1/3) "... The range of nonnegative...
17
8029
by: Christopher Dyken | last post by:
Hi group, I'm trying to implement two routines to handle 32x32-bits and 64x64-bits signed integer multiplication on a 32 bits machine in C. It easy to find descriptions of non-signed multiplication, however, I haven't found any good descriptions for the signed counterpart. Does any of you have a good reference for this topic? Thanks in advance,
9
4178
by: dam_fool_2003 | last post by:
For int data type the default range starts from signed to unsigned. If we don't want negative value we can force an unsigned value. The same goes for long also. But I don't understand why we have signed char which is -256. Does it means that we can assign the same ASCII value to both signed and unsigned. That means the ASCII value can be represented with a type of signed char and also unsigned char? For example int main(void) {
10
15664
by: tinesan | last post by:
Hello fellow C programmers, I'm just learning to program with C, and I'm wondering what the difference between signed and unsigned char is. To me there seems to be no difference, and the standard doesn't even care what a normal char is (because signed and unsigned have equal behavior). For example if someone does this: unsigned char a = -2; /* or = 254 */
22
5622
by: juanitofoo | last post by:
Hello, I've just switched to gcc 4 and I came across a bunch of warnings that I can't fix. Example: #include <stdio.h> int main() { signed char *p = "Hola";
10
3310
by: =?iso-8859-2?B?SmFuIFJpbmdvuQ==?= | last post by:
Hello everybody, this is my first post to a newsgroup at all. I would like to get some feedback on one proposal I am thinking about: --- begin of proposal --- Proposal to add signed/unsigned modifier to class declarations to next revision of C++ programming language
4
4640
by: Chris | last post by:
How do we create digitally signed MDE files in Access 2007 ? I tried to follow the procedure I was using in other office versions. 1. I installed the Verisign certificate (with private key). 2. Signed the MDB from VBA. 3. Create the MDE. When I try to open the signed MDE, even on the developement machine with
7
5049
by: somenath | last post by:
Hi All, I am trying to undestand "Type Conversions" from K&R book.I am not able to understand the bellow mentioned text "Conversion rules are more complicated when unsigned operands are involved. The problem is that comparisons between signed and unsigned values are machine- dependent, because they depend on the sizes of the various integer types. For example, suppose that int is 16 bits
6
6458
by: Kislay | last post by:
Consider the following code snippet unsigned int i=10; int j= - 2; // minus 2 if(i>j) cout<<"i is greater"; else cout<<"j is greater"; Since i is unsigned , j is greater . I know why , but vaguely . Can
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9481
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
10341
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...
1
10095
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
8979
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
6741
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
5383
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
4054
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
2
3656
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.