[c] Simple int to char[] conversion

I have a simple question

How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?

Thanks

This question is related to c character-encoding

The answer is


main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
// Now str contains the integer as characters
}

Hope it will be helpful to you.


#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;

itoa(a,arr,10) ;   // itoa() is a function of stdlib.h file that convert integer 
                   // int to array itoa( integer, targated array, base u want to             
                   //convert like decimal have 10 

for( int i= 0 ; i < strlen(arr); i++)   //  strlen()   function in string file thar return string length
  printf("%c",arr[i]);

}

If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:

int x;
char c = '0' + x;

Now, if you want a character string, just add a terminating '\0' char:

char s[] = {'0' + x, '\0'};

Note that:

  1. You must be sure that the int is in the 0-9 range, otherwise it will fail,
  2. It works only if character codes for digits are consecutive. This is true in the vast majority of systems, that are ASCII-based, but this is not guaranteed to be true in all cases.

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)


Questions with c tag:

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? How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption How does one set up the Visual Studio Code compiler/debugger to GCC? How to add a char/int to an char array in C? Fork() function in C Warning comparison between pointer and integer Unsigned values in C How to run C program on Mac OS X using Terminal? How to printf a 64-bit integer as hex? Casting int to bool in C/C++ Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); "Multiple definition", "first defined here" errors error C4996: 'scanf': This function or variable may be unsafe in c programming Fatal error: iostream: No such file or directory in compiling C program using GCC What is the symbol for whitespace in C? How to change text color and console color in code::blocks? How to build x86 and/or x64 on Windows from command line with CMAKE? error: expected primary-expression before ')' token (C) C compile : collect2: error: ld returned 1 exit status How to use execvp() What does "collect2: error: ld returned 1 exit status" mean? socket connect() vs bind() fatal error: mpi.h: No such file or directory #include <mpi.h> How to scanf only integer? Abort trap 6 error in C Can someone explain how to append an element to an array in C programming? Returning string from C function Difference between using Makefile and CMake to compile the code How to convert const char* to char* in C? C convert floating point to int "break;" out of "if" statement? How to compile and run C in sublime text 3? How do I use setsockopt(SO_REUSEADDR)? Reading string by char till end of line C/C++ How to set all elements of an array to zero or any same value? The differences between initialize, define, declare a variable how to stop a loop arduino 'readline/readline.h' file not found size of uint8, uint16 and uint32? warning: control reaches end of non-void function [-Wreturn-type] Char Comparison in C

Questions with character-encoding tag:

Changing PowerShell's default output encoding to UTF-8 JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10) Change the encoding of a file in Visual Studio Code What is the difference between utf8mb4 and utf8 charsets in MySQL? How to open html file? All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"? UTF-8 output from PowerShell ERROR 1115 (42000): Unknown character set: 'utf8mb4' "for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte How to make php display \t \n as tab and new line instead of characters Is ASCII code 7-bit or 8-bit? How to make Unicode charset in cmd.exe by default? How can I transform string to UTF-8 in C#? Meaning of - <?xml version="1.0" encoding="utf-8"?> java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...' How can I determine the character encoding of an excel file? How to remove non UTF-8 characters from text file How to read text files with ANSI encoding and non-English letters? Force encode from US-ASCII to UTF-8 (iconv) PHP Curl UTF-8 Charset json_encode(): Invalid UTF-8 sequence in argument Setting PHP default encoding to utf-8? What does "Content-type: application/json; charset=utf-8" really mean? How to support UTF-8 encoding in Eclipse Error: unmappable character for encoding UTF8 during maven compilation PHP DOMDocument loadHTML not encoding UTF-8 correctly SQL Server - Convert varchar to another collation (code page) to fix character encoding PHP: Convert any string to UTF-8 without knowing the original character set, or at least try Strange Characters in database text: Ã, Ã, ¢, â‚ €, No line-break after a hyphen Best way to convert string to bytes in Python 3? PHP decoding and encoding json with unicode characters HMAC-SHA256 Algorithm for signature calculation What is the difference between UTF-8 and ISO-8859-1? Text file with 0D 0D 0A line breaks Python: Converting from ISO-8859-1/latin1 to UTF-8 FPDF utf-8 encoding (HOW-TO) Working with UTF-8 encoding in Python source How to set the "Content-Type ... charset" in the request header using a HTML link How to convert an entire MySQL database characterset and collation to UTF-8? Writing Unicode text to a text file? Spring MVC UTF-8 Encoding Converting byte array to String (Java) UTF-8 encoding problem in Spring MVC UTF-8 encoded html pages show ? (questions marks) instead of characters Convert byte[] to char[] How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript? li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery? SQL Server default character encoding How to convert these strange characters? (ë, Ã, ì, ù, Ã)