开发者

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 outp开发者_JAVA技巧uts 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', or someValue + 'A', because I find it a bit easier to follow the code.


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

 printf("%c", numbers[i] + 'a');

This will the ascii character not the decimal representation to the 'console'.

Also, you do not need typedef.


A more general solution doesn't assume ASCII but works with the compiler's execution character set.

char *vec = "abcdefghijklmnopqrstuvwxyz";
printf("'%c'", vec[0]); //prints 'a'

And you can reverse the operation

int i = strchr(vec, 'm')-vec;

Since strchr returns a pointer to the character, subtracting the base yields a ptrdiff_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 a ptrdiff from two addresses that are not part of the same 'object'; you'd probably get a meaningless negative number.


void dispSet(set numbers[], int size_numbers) {
  int i;
  printf("[ ");
  for (i = 0; i < size_numbers-1; i++) {
    printf("%d, ", ((char) numbers[i]) - '0');
  }
  printf("%d ]", ((char) numbers[size_numbers-1]) - '0');
  printf("\n");
}

This change converts a number or any character to its ASCII value


This answer is late

Cast it like this: (char) i

char c = (char) i // Cast not needed on variable assignment
                  // It's recommended to put it there, no complications needed

For code-golfing contests (just in case), use (char)i and char c=i; appropriately. PPCG.GA for such contests.


You can use Character.toChars(x + 97)[0] to get the char value, or just cast with (char) (x + 97).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜