C++ ASCI int values

Hi All,

I'm currently fiddling about trying to learn C++ and wrote a little program that outputs the ASCI values for numbers 0-255 but it's got a problem...

For the numbers 255 thru 128 it shows a negative number. For numbers 127-0 (my loop decrements) it shows the correct numerical value...

Here's my loop:

	for (c=255; c>0; c--)
	{
		// output the value of c
		printf ("%d : ",c);
		// make variable chChar the value of c
		chChar = c;
		// output asci value of chChar
		cout << chChar << " : " << (int)chChar << endl;
	}

I'm I hitting an overflow or something?

Many thanks :slight_smile:

Hi,
By default the char would be a signed char.
That is the reason you are getting negative and positive values.
Please correct it by replacing - "char" with "unsigned char;"

Hope it resolves your problem.

Have a Good Day !!!

Thanks GaneshCPUX that solved the problem :slight_smile:

...Now I have to get my head around why it fixed the problem :wink:

EDIT: Ahh yes of course, a signed char has 1 byte - an unsigned has that extra bit to toggle hense can go over 127 :slight_smile:

Nope. Both the signed and the unsigned char type are 1 Byte (8 bits) in size. The difference is that for a signed type, the MSB (most significant bit) is the sign indicator. So an unsigned char can go from 0 (0000 0000) to 255 (1111 1111), while a signed goes from 0 (0000 0000) to 127 (0111 1111) and -128 (1000 0000) to -1 (1111 1111)

Ahh, yes. I think I've got it. Both have the same number of bits available but the signed char has the MSB reserved for its sign indicator.

It's good to get the basics down early on :smiley:

Thanks for your help :smiley:

The C99 standard (ISO/IEC 9899:1999) only requires the range -127 (SCHAR_MIN) to
+127 (SCHAR_MAX) for objects of type signed char. However -128 is valid for 8-bit
signed chars if 2s complement representation is used (which it almost always is).

Note also that there are actually three char types (See C99, 6.2.5.14 and 6.2.5.15)
The three types char, signed char, and unsigned char are collectively called
the character types. The implementation shall define char to have the same range,
representation, and behavior as either signed char or unsigned char.

Which is why I always declare the type explicitly.