tabaluga
tabaluga

Reputation: 1417

How do I convert an integer to a character in c?

This works:

int  a = 7;

char b = a + '0';

write(1,&b,1);

but this does not:

int a = 7;

char b = (char) a;

write(1,&b,1);

Could someone tell me why? I just want to convert the integer 7 to '7' as a character.

Upvotes: 0

Views: 207

Answers (2)

Felipe_SC
Felipe_SC

Reputation: 19

To convert an integer to a string you can use the sprintf(). The answer can be found in another topic: implicit declaration of function itoa is invalid in c99

Here is the code posted in the answer of Deekshith Patil:

#include <stdio.h> 

int main()
{
int load = 15;
char buffer[100];

sprintf(buffer,"%d",load);

printf("buffer in int = %s\n",buffer);
    return 0;
}

This will take your integer value and convert it to a string.

Upvotes: 0

John Bode
John Bode

Reputation: 123458

Remember that char is just a narrow integer type - on most systems it's 8 bits wide, meaning it can store values from [-128..127] (signed) or [0..255] (unsigned)1.

When you write

int a = 7;
char b = (char) a;

you're still assigning the integer value 7 to b - it's just being stored in a narrower integer type. It's not being converted to the encoding for the character symbol '7'.

In ASCII and UTF-8, the encoding for the character symbol '7' is 55. The encoding for the character symbol '0' is 48, so you can add 7 to '0' to get the encoding for the character '7'.

The value 7 is the encoding for the ASCII control character BEL - it rings the bell on the console.


  1. Plain char may be signed or unsigned depending on the platform.

Upvotes: 2

Related Questions