[c++] Convert an int to ASCII character

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.

This question is related to c++ c ascii

The answer is


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;
}

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/


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;


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.)


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


"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.


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;

          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.


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)


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to ascii

Detect whether a Python string is a number or a letter Is there any ASCII character for <br>? UnicodeEncodeError: 'ascii' codec can't encode character at special name Replace non-ASCII characters with a single space Convert ascii value to char What's the difference between ASCII and Unicode? Invisible characters - ASCII How To Convert A Number To an ASCII Character? Convert ascii char[] to hexadecimal char[] in C Convert character to ASCII numeric value in java