diego9403
diego9403

Reputation: 153

Addition ASCII in c++

I would like to change my char variable.

using namespace std;    

int main()
{
    char q;
    q='b';
    char c=127;
    //cout << (int)q  << endl<< static_cast<int>('z');
    char d= static_cast<char>(static_cast<int>((static_cast<int>('z') +19)));
    cout << (int)d << endl;
    system("pause");
}

Intupt:

-115

Why after addition variable assigned -115?

Upvotes: 0

Views: 231

Answers (2)

LL.Li
LL.Li

Reputation: 1

122 + 19 = 141 --> 1000 1101 binary

type char here might be 8 bits signed int,so the first bit '1' is its sign bit.

1000 1101 is what it's like in the computer memory.

But computers usually use ones-complement code to present negative number.

The true code of 1000 1101 is 1111 0011,int the same way,the first '1' is its sign bit, so 1111 0011 is exactly -115 in 10base

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234705

On your platform, char is an 8 bit signed 2's complement type. You are actually overflowing this type and the behaviour of overflowing a signed integral type is undefined in C++. Don't do it.

Notes:

  1. 8 bit is mandated by the standard.

  2. char can be unsigned or signed.

  3. If unsigned it must have the range [0, 255], and 255 + 1 will be 0. Overflow for an unsigned type is defined.

  4. If signed it can either have the range -128 to +127 or -127 to +127. The latter range (1's complement) is not allowed from C++14. (Interestingly that's not a breaking change since a difference in moving from 1's to 2's complement would only be observable in a malformed program such as yours, if at all!)

A simple remedy? Use unsigned char.

Upvotes: 1

Related Questions