Weqk
Weqk

Reputation: 21

How to convert an int to ASCII char C++

I have to convert an int to an ASCII string. Basically, i want this :

    int iTest = 128;
    char ca[3];
??? --> **SOLUTION :** sprintf(ca,"%d",iTest);

and the result :

 ca[0] = 0x31;--> Hexcode of '1'
 ca[1] = 0x32;
 ca[2] = 0x38;

Upvotes: 0

Views: 6574

Answers (3)

masoud
masoud

Reputation: 56529

Use std::string and std::to_string :

#include <string>
#include <iostream>

using namespace std;

...

int iTest = 128;

string ca = to_string(iTest);

for (int i = 0; i < ca.size(); i++)
{
    cout << hex << "0x" << (int) ca[i] << endl;
}

Result:

0x31
0x32
0x38

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409432

Use the modulo and division operators to get each digit, then print each digit adding '0'.

Upvotes: 0

Kiril Kirov
Kiril Kirov

Reputation: 38173

for each digit
    ca[ i ] = digit + '0';

Notes:

  • note the different lengths of the number
  • allocate ca dynamically, based on the "length" of the number (the number of digits)
  • iterating over each digit can be done by using % and / operators for modulo and division.

Upvotes: 0

Related Questions