Convert an int to ASCII character

C++CAscii

C++ Problem Overview


I have

int i = 6;

and I want

char c = '6'

by conversion. Any simple way to suggest?

EDIT: also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an ifstream.

C++ Solutions


Solution 1 - C++

Straightforward way:

char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];

Safer way:

char aChar = '0' + i;

Generic way:

itoa(i, ...)

Handy way:

sprintf(myString, "%d", i)

C++ way: (taken from Dave18 answer)

std::ostringstream oss;
oss << 6;

Boss way:

> Joe, write me an int to char converter

Studboss way:

> char aChar = '6';

Joe's way:

> char aChar = '6'; //int i = 6;

Nasa's way:

> //Waiting for reply from satellite...

Alien's way: '9'

> //Greetings.

God's way:

> Bruh I built this

Peter Pan's way:

char aChar;

switch (i)
{
  case 0:
    aChar = '0';
    break;
  case 1:
    aChar = '1';
    break;
  case 2:
    aChar = '2';
    break;
  case 3:
    aChar = '3';
    break;
  case 4:
    aChar = '4';
    break;
  case 5:
    aChar = '5';
    break;
  case 6:
    aChar = '6';
    break;
  case 7:
    aChar = '7';
    break;
  case 8:
    aChar = '8';
    break;
  case 9:
    aChar = '9';
    break;
  default:
    aChar = '?';
    break;
}

Santa Claus's way:

//Wait till Christmas!
sleep(457347347);

Gravity's way:

> //What

'6' (Jersey) Mikes'™ way:

> //

SO way:

> Guys, how do I avoid reading > beginner's guide to C++?

My way:

> or the highway.

Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.

Edit: satisfied?

Solution 2 - C++

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

It works by adding the ASCII value of char '0' to the integer digit.

int i=6;
char c = '0'+i;  // now c is '6'

For example:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letter of the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

Adjust as appropriate for your specific situation.
(and test-test-test! any code you write)

Solution 3 - C++

Just FYI, if you want more than single digit numbers you can use sprintf:

char txt[16];
int myNum = 20;
sprintf(txt, "%d", myNum);

Then the first digit is in a char at txt[0], and so on.

(This is the C approach, not the C++ approach. The C++ way would be to use stringstreams.)

Solution 4 - C++

This is how I converted a number to an ASCII code. 0 though 9 in hex code is 0x30-0x39. 6 would be 0x36.

unsigned int temp = 6;
or you can use unsigned char temp = 6;
unsigned char num;
 num = 0x30| temp;

this will give you the ASCII value for 6. You do the same for 0 - 9

to convert ASCII to a numeric value I came up with this code.

unsigned char num,code;
code = 0x39; // ASCII Code for 9 in Hex
num = 0&0F & code;

Solution 5 - C++

My way to do this job is:

char to int
char var;
cout<<(int)var-48;
    
int to char
int var;
cout<<(char)(var|48);

And I write these functions for conversions:

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='\0'){
            break;
        }else{
            results*=10;
            results+=(int)szBroj[counter]-48;
            counter++;
        }
    }
    return results;
}

char * int2char(int iNumber){
    int iNumbersCount=0;
    int iTmpNum=iNumber;
    while(iTmpNum){
        iTmpNum/=10;
        iNumbersCount++;
    }
    char *buffer=new char[iNumbersCount+1];
    for(int i=iNumbersCount-1;i>=0;i--){
        buffer[i]=(char)((iNumber%10)|48);
        iNumber/=10;
    }
    buffer[iNumbersCount]='\0';
    return buffer;
}

Solution 6 - C++

Solution 7 - C++

I suppose that

std::to_string(i)

could do the job, it's an overloaded function, it could be any numeric type such as int, double or float

Solution 8 - C++

Alternative way, But non-standard.

int i = 6;
char c[2];
char *str = NULL;
if (_itoa_s(i, c, 2, 10) == 0)
   str = c;

Or Using standard c++ stringstream

 std::ostringstream oss;
 oss << 6;

Solution 9 - C++

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

Solution 10 - C++

Doing college work I gathered the data I found and gave me this result:

"The input consists of a single line with multiple integers, separated by a blank space. The end of the entry is identified by the number -1, which should not be processed."

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
	char numeros[100]; //vetor para armazenar a entrada dos numeros a serem convertidos
	int count = 0, soma = 0;

	cin.getline(numeros, 100);

	system("cls"); // limpa a tela

	for(int i = 0; i < 100; i++)
	{
		if (numeros[i] == '-') // condicao de existencia do for
			i = 100;
		else
		{
			if(numeros[i] == ' ') // condicao que ao encontrar um espaco manda o resultado dos dados lidos e zera a contagem
			{
				if(count == 2) // se contegem for 2 divide por 10 por nao ter casa da centena
					soma = soma / 10;
				if(count == 1) // se contagem for 1 divide por 100 por nao ter casa da dezena
					soma = soma / 100;


				cout << (char)soma; // saida das letras do codigo ascii
				count = 0;

			}
			else
			{
				count ++; // contagem aumenta para saber se o numero esta na centena/dezena ou unitaria
				if(count == 1)
					soma =  ('0' - numeros[i]) * -100; // a ideia é que o resultado de '0' - 'x' = -x (um numero inteiro)
				if(count == 2)
					soma = soma + ('0' - numeros[i]) * -10; // todos multiplicam por -1 para retornar um valor positivo
				if(count == 3)
					soma = soma + ('0' - numeros[i]) * -1; /* caso pense em entrada de valores na casa do milhar, deve-se alterar esses 3 if´s
		alem de adicionar mais um para a casa do milhar. */
			}
		}
	}

	return 0;
}

The comments are in Portuguese but I think you should understand. Any questions send me a message on linkedin: https://www.linkedin.com/in/marcosfreitasds/

Solution 11 - C++

          A PROGRAM TO CONVERT INT INTO ASCII.




          #include<stdio.h>
          #include<string.h>
          #include<conio.h>

           char data[1000]= {' '};           /*thing in the bracket is optional*/
           char data1[1000]={' '};
           int val, a;
           char varray [9];

           void binary (int digit)
          {
              if(digit==0)
               val=48;
              if(digit==1)
               val=49;
              if(digit==2)
               val=50;
              if(digit==3)
               val=51;
              if(digit==4)
               val=52;
              if(digit==5)
               val=53;
              if(digit==6)
               val=54;
              if(digit==7)
               val=55;
              if(digit==8)
               val=56;
              if(digit==9)
                val=57;
                a=0;

           while(val!=0)
           {
              if(val%2==0)
               {
                varray[a]= '0';
               }

               else
               varray[a]='1';
               val=val/2;
               a++;
           }


           while(a!=7)
          {
            varray[a]='0';
            a++;
           }


          varray [8] = NULL;
          strrev (varray);
          strcpy (data1,varray);
          strcat (data1,data);
          strcpy (data,data1);

         }


          void main()
         {
           int num;
           clrscr();
           printf("enter number\n");
           scanf("%d",&num);
           if(num==0)
           binary(0);
           else
           while(num>0)
           {
           binary(num%10);
           num=num/10;
           }
           puts(data);
           getch();

           }

I check my coding and its working good.let me know if its helpful.thanks.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser963241View Question on Stackoverflow
Solution 1 - C++Eugene Mayevski 'CallbackView Answer on Stackoverflow
Solution 2 - C++abelenkyView Answer on Stackoverflow
Solution 3 - C++Nathan S.View Answer on Stackoverflow
Solution 4 - C++DoratoView Answer on Stackoverflow
Solution 5 - C++aleksandar kamenjasevicView Answer on Stackoverflow
Solution 6 - C++NewbieView Answer on Stackoverflow
Solution 7 - C++IceSeaView Answer on Stackoverflow
Solution 8 - C++cpxView Answer on Stackoverflow
Solution 9 - C++junView Answer on Stackoverflow
Solution 10 - C++Marcos Freitas BrazilView Answer on Stackoverflow
Solution 11 - C++nishant vermaView Answer on Stackoverflow