Say I have a number 0
that corresponds to the ASCII character a
. How would I go about converting a number in the range 0
to 25
to letters in the alphabet?
I have already tried adding 97
to the decimal value, but it just outputs the number+97
.
typedef enum {
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
} set;
void dispSet(set numbers[], int size_numbers) {
int i;
printf("[ ");
for (i = 0; i < size_numbers-1; i++) {
printf("%d, ", ((char) numbers[i])+97);
}
printf("%d ]", ((char) numbers[size_numbers-1])+97);
printf("\n");
}
You should should be pasing
%c
to printf, not%d
. The format specifier, tells printf how to interpret the supplied paramters. If you pass%d
, it will interpret the arguments as an integer. By specifying%c
, you tell it to interpret the argument as a character. The manpages / help for printf, eventually lead to some 'format specifiers', which gives you the full list.Personally, I tend to use
someValue + 'a'
, orsomeValue + 'A'
, because I find it a bit easier to follow the code.Cast it like this:
(char) i
For code-golfing contests (just in case), use
(char)i
andchar c=i;
appropriately. PPCG.GA for such contests.A more general solution doesn't assume ASCII but works with the compiler's execution character set.
And you can reverse the operation
Since
strchr
returns a pointer to the character, subtracting the base yields aptrdiff_t
representing the offset between the two "points", this offset is the ordinal of the member of the sequence. But only if the character is present, otherwise it's undefined behavior to take aptrdiff
from two addresses that are not part of the same 'object'; you'd probably get a meaningless negative number.This change converts a number or any character to its ASCII value
The algorithm is to 'a' to your numbers, which you have already done by adding 97. However you should use character specifier instead of the decimal specifier in the
printf
This will the ascii character not the decimal representation to the 'console'.
Also, you do not need typedef.
You can use Character.toChars(x + 97)[0] to get the char value, or just cast with (char) (x + 97).