Reputation: 372
How do I convert this array with ASCII numbers to text, so every number get's a letter. So "72" gets H, 101 gets E and so on.
int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
Upvotes: 1
Views: 1362
Reputation: 11
You can use array of structs since the array may contain different data type. Try this:
#include <stdio.h>
struct data
{
int j;
char c;
};
int main()
{
int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
int size = sizeof(a)/sizeof(a[0]);
struct data value[size];
for(int i=0;i<size;i++)
{
if(a[i]>=48 && a[i]<=57)
{
char ch= a[i];
value[i].j =ch;
}
else
{
char ch= a[i];
value[i].c =ch;
}
}
for(int i=0;i<size;i++){
if(a[i]>=48 && a[i]<=57)
printf("%d",value[i].j);
printf("%c",value[i].c);
}
return 0;
}
Output will be: Hello World (Hope it helps.)
Upvotes: 0
Reputation: 213701
Everything in C is numbers. The compiler can't tell a difference between the integer constant 72
and 'H'
, either results in a number and they even both have the type int
. Characters and number formats only apply when you present raw data to a human user.
So there's no converting 72
to 'H'
, it's already in the correct format, the raw number 72. We simply need to tell the computer that we want this raw number to get printed as a character. The simplest way is printf("%c", ...
but that one expects a parameter of type char
. So we would have to convert the a[0]
from int
type to char
, which we can do by means of a cast. printf("%c", (char)a[0]);
.
Had the array been char a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
then the cast wouldn't be necessary.
Upvotes: 1
Reputation: 788
int main(int argc, char *argv[], char **env) {
int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
for (int i = 0; i < sizeof a / sizeof(int); ++i) {
printf("%c", (char) a[i]);
}
}
Upvotes: 2
Reputation: 1584
You can iterate over the array, and use the %c
formating parameter to print the ascii characters of the int value
for (int i = 0 ; i < 11; i ++){
printf("%c", a[i]);
}
Upvotes: 4