0

The question has nothing to do with CS50, so it could be voted as off-topic, but I personally find it curious. The question is that several years ago I wrote a program to convert an array of integers into a string, not in the sense in which the function itoa() does it, but in a chain of alphabetic characters only, in this case the number stored in the array is transformed into my wife's name.

#include <stdio.h>

int main(void)
{
    int num[2] = {1769234766,10};
    printf("%s",(char*)num);
}

The output is "Nati" including a new line character. I certainly do not know why this is so and I am unable to remember it, but when reviewing these old programs this one is torturing me (damn documentation). I have the feeling that something elementary escapes me but for my life I am not able to see it. It seems that the comparison with the ascii code has not been successful, I have tried to see some similitude in decimal, octal, hexadecimal, but I am not able to find a relationship, I would like someone to take a look to see if it is clearer than I (Well, it may be a lot to ask but I also try to help when I have a little time) Thank you.

3

Follow the numbers. Decimal 1769234766 = hex 6974614E. Now, look at the hex pairs, stored right to left:

4E = N
61 = a
74 = t
69 = i

The line feed is easy enough to understand.

I'll leave it to you to research how numbers are physically stored in memory as integers and chars. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on fourm maintenance. ;-)

| improve this answer | |
  • Thank you for this, I was puzzled by the typecast as well and couldn't find anything in the debugger or on google. – Allan Clayton Jul 30 '18 at 20:57
  • Thank you very much. How stupid! I did not remember little-endian, so I tried to make the association the reverse, thank you very much – MARS Jul 30 '18 at 21:03
  • is the 10 just there to tell the compiler what base the number is in? – Allan Clayton Jul 30 '18 at 21:04
  • Allan, what's the ASCII for linefeed in decimal? – Cliff B Jul 30 '18 at 21:06
  • ooohhhhh I see now haha – Allan Clayton Jul 30 '18 at 21:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .