SPB
SPB

Reputation: 4218

How to cast an int variable to char in C++?

char a[3];

int x=9;
int y=8;

a[0]=(char)x;
a[1]=(char)y;
a[2]='\0';

unsigned char * temp=(unsigned char*)a;

but when i am displaying this temp, it's displaying ?8. should display 98.

can anyone please help???

Upvotes: 1

Views: 3242

Answers (6)

Alexandre C.
Alexandre C.

Reputation: 56986

a[0] = (char)x; 
a[1] = (char)y; 

should be

a[0] = x + '0'; 
a[1] = y + '0'; 

(keep the cast if you want to disable warnings)/

Upvotes: 0

stinky472
stinky472

Reputation: 6797

Something like nico's solution is what you should be using (also see boost::lexical_cast if you have boost), but for a direct answer to your question (if you want to understand things at a lower level, e.g.), the string [9, 8, \0] is not "98".

"98" is actually [57, 56, 0] or [0x39, 0x38, 0x0] in ASCII. If you want to concatenate decimal numbers ranging from 0 to 9 this way manually, you'll have to add '0' (0x30) to them. If you want to deal with numbers exceeding that range, you'll have to do more work to extract each digit. Overall, you should use something like the toString function template nico posted or boost::lexical_cast for a more complete version.

Upvotes: 1

Not-a-Ninja
Not-a-Ninja

Reputation: 1

There are two ways of doing it:

  1. Use itoa()
  2. add 0x30 (== '0') to each digit

Of course the 2nd method works only for single digits, so you'd rather use itoa() in a general case.

Upvotes: 0

Poni
Poni

Reputation: 11337

char a[3];

int x='9';
int y='8';

a[0]=(char)x;
a[1]=(char)y;
a[2]='\0';

unsigned char * temp=(unsigned char*)a;
printf("%s", temp);

You were giving a value of 9 and 8, instead of their ASCII values.

Upvotes: 4

nico
nico

Reputation: 51680

Or, more generic

template <class T> string toString (const T& obj)
    {
    stringstream ss;
    ss << obj;
    return ss.str();
    }

Upvotes: 1

Goz
Goz

Reputation: 62333

Try using itoa or sprintf

Event better, given that you are using C++ try using stringstream. You can then do it as follows

std::stringstream stream;
stream << x << y;

Upvotes: 4

Related Questions