Reputation: 5
been searching everywhere, but couldn't the correct answer.
the problem is pretty simple:
i have to convert ASCII integer values into char's. for example, according to ASCII table, 108 stands for 'h' char. But when i try to convert it like this:
int i = 108
char x = i
and when I printf it, it shows me 's', no matter what number i type in(94,111...).
i tried this as well:
int i = 108;
char x = i + '0'
but i get the same problem! by the way, i have no problem in converting chars into integers, so i don't get where's the problem :/ thanks in advance
Upvotes: 0
Views: 622
Reputation: 8255
Sounds to me like your printf
statement is incorrect.
Doing printf("%c", c)
where c has the value 108 will print the letter l
... If you look at http://www.asciitable.com/ you'll see that 108 is not h
;)
Upvotes: 1
Reputation: 50928
That is how you do it. You probably want it unsigned, though.
Maybe your printf
is wrong?
The following is an example of it working:
// Print a to z.
int i;
for (i = 97; i <= 122; i++) {
unsigned char x = i;
printf("%c", x);
}
This prints abcdefghijklmnopqrstuvwxyz
as expected. (See it at ideone)
Note, you could just as well printf("%c", i);
directly; char
is simply a smaller integer type.
If you're trying to do printf("%s", x);
, note that this is not correct. %s
means print as string, however a character is not a string.
If you do this, it'll treat the value of x
as a memory address and start reading a string from there until it hits a \0
. If this merely resulted in printing s
, you're lucky. You're more likely to end up getting a segmentation fault doing this, as you'll end up accessing some memory that is most likely not yours. (And almost surely not what you want.)
Upvotes: 1
Reputation: 37500
I'm guessing your printf statement looks like this:
printf("s", x);
..when in fact you probably meant:
printf("%s", x);
...which is still wrong; this is expecting a string of characters e.g:
char* x = "Testing";
printf("%s", x);
What you really want is this:
int i = 108;
char x = i + '0';
printf("%c", x);
...which on my system outputs £
Upvotes: 0