You are here:

C++/data type in c++

Advertisement


Question
QUESTION: hello sir!
         i have problem with signed and unsigned char.
if i declare  unsigned char ch=-123; its output is same as if i use signed instead of unsigned. then what is use unsigned .then why we take unsigned take values from 0 to 255.

ANSWER: Hai dear Deepak !

Certainly there is a difference upon using unsigned and signed data types !

take a look at this small programme

#include<iostream.h>

void main()
{
 unsigned char a = - 123;
 signed char b = -123;


 cout<<(int)a;
 cout<<(int)b;
}

O/P Of this program is 133 -123 , note that the results were not same , in a signed char the last bit (MSB) will be used for storing the sign and hence it just allows -128 to 127 for signed integer , in case of unsigned integer , all the bits are used to store the values and hence you are free to store from 0 to 255 !

Thanks and Regards !
Prince M. Premnath

---------- FOLLOW-UP ----------

QUESTION: then how output will be 133 of a. -123 of b is understandable . but if -123 is stored as 01111011.how it represent 133.

Answer
Hai dear Deepak !

 While assigning a -ve number to an unsigned char type , it will take few modification in internal representation ,say the MSB will be set to 0 and all other bit were set to 1 if the value assigned to unsigned char is -1 and so on for all other values within the accepted range !

Thanks and Regards!
Prince M. Premnath

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.