Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why did the number 4 after adding the symbol “0” become the symbol “4”?

I wrote a program that prints the same number that was passed as an argument. The code works, but I don’t understand the process of converting numbers to characters. How does this work at the machine level? Why, when I add the zero symbol, do I get the four symbol from the number 4?

#include <stdio.h>

void    ft_putchar(char c)
{
    write(1, &c, 1);
}

void    ft_putnbr(int nb)
{
    if (nb >= 10)
    {
        ft_putnbr(nb / 10);
        ft_putnbr(nb % 10);
    }
    else
    {
        ft_putchar(nb + '0');
    }
}

int main()
{
    ft_putnbr(42);
    return 0;
}

I don’t understand the process of converting a number into a symbol in this case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

'0' is just the human readable represetation of the integer 48 which is considered as code for the character '0' in ASCII.

ASCII digit codes:

decimal octal hex binary character
48 060 30 0110000 0
49 061 31 0110001 1
50 062 32 0110010 2
51 063 33 0110011 3
52 064 34 0110100 4
53 065 35 0110101 5
54 066 36 0110110 6
55 067 37 0110111 7
56 070 38 0111000 8
57 071 39 0111001 9

When you add 4 to 48 which is integer representation of '0' you are getting 52.

When you write it to the screen then the character represented by its code is displayed (in this case '4')

Also C standard guarantees that digit characters codes will be consecutive and ordered the natural way (ie '0' lowest value and '9' the highest)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading