i am having problem in type casting,the result of the following code is giving -64, however it should be 192, why this is so?

#include <iostream>
using namespace std;

int main()
{
	int a;

	a=char (192);
	cout<<a;

	return 0;
}

i am having problem in type casting,the result of the following code is giving -64, however it should be 192, why this is so?

The problem is that a type char is signed by default. Since a type char is one byte (8 bits) then that means the highest order bit is used as a sign bit, leaving only 7 bits to represent a char. The constant 192 requires more than 7 bits to be represented.

Here is 192 in binary: 1100 0000. Now if you drop those bits into an 8 bit signed char, like you are doing, then what do you get? Well, the left most bit becomes the sign bit denoting negative and then the remaining bits (100 0000) equals 64.

Try changing the char to an unsigned type.

commented: Nice explanation. +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.