-2

For example:

  • "16" should print out the decimal values: 49,54
  • "24" should print out the decimal values: 50,52

How do I achieve this?

Victor B.
  • 248
  • 2
  • 11
  • 2
    This question shows you how to do it: http://stackoverflow.com/questions/1472581/printing-chars-and-their-ascii-code-in-c – Bert Jan 18 '16 at 20:31
  • That is not the same question that I am asking. The answer below answered my question. – Victor B. Jan 18 '16 at 20:39

1 Answers1

6

It's really simple, you don't need to convert anything it's a matter of representation, example

const char *sixteen = "16";
const char *twentyfour = "24";
const char *number = "1345461";

printf("%d,%d\n", sixteen[0], sixteen[1]);
printf("%d,%d\n", twentyfour[0], twentyfour[1]);
//       ^  ^ use the `%d' specifier to see the decimal value
//            of the corresponding ascii.
for (int i = 0 ; number[i] != '\0' ; ++i)
    printf("%d,", number[i]);
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Thank you. I'm beginning to learn C and was not aware of that syntax. – Victor B. Jan 18 '16 at 20:33
  • Is this the bit where we point out that C isn't actually required to use ASCII? Of course if you're using a computer in grandad's basement you've probably found that out... – Persixty Jan 18 '16 at 20:42
  • 1
    On a serious note I would point out that this works because there's an implicit promotion of `char` to `int` when arguments are passed to variadic functions. – Persixty Jan 18 '16 at 20:43
  • 1
    @DanAllen Important observation, will leave it as a comment if you don't mind. – Iharob Al Asimi Jan 18 '16 at 20:44
  • 1
    @DanAllen to be fair, Granddad probably doesn't have a System/3x0 or Univac mainframe, running a non-UN\*X OS, in the basement. :-) But, yes, C on IBM's System/3x0 and z/Architecture OSes, and on IBM i, use EBCDIC, not ASCII; however, the same technique works, it just prints *EBCDIC* codes for characters rather than *ASCII* codes. –  Jan 18 '16 at 20:48
  • @GuyHarris The question did specifically ask for ASCII. So kids if you *don't* get 49,54 and 50,52 tell grandpa you got it working! – Persixty Jan 18 '16 at 20:51
  • 1
    @DanAllen "tell grandpa you got it working" And offer to help with the electrical bill for the machine. :-) –  Jan 18 '16 at 23:11