Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a integers between 0 and 25 to corresponding ASCII characters?

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");
}
like image 378
tekknolagi Avatar asked Dec 11 '25 09:12

tekknolagi


1 Answers

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', or someValue + 'A', because I find it a bit easier to follow the code.

like image 122
forsvarir Avatar answered Dec 13 '25 03:12

forsvarir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!