The binary number is stored in the character array num2and1, this value is stored here: 110000110001

I want to thrust its int variable and then convert the number to decimal, and from it already into the ASCII character, and then write the received symbol into the file

For this I use the code from the book K & R

long n; n = 0; for (i = 0; num2and1[i] >= '0' && num2and1[i] <= '9'; ++i) n = 10 * n + (num2and1[i] - '0'); printf("%d", n); 

But the output is -1669039695. How can you correctly transfer these characters of numbers 1 and 0 to int? And why is there no binary representation of numbers in C?

  • one
    "But the output is -1669039695." - and what should? It can be seen that this is a code for decimal notation, the range of digits from '0' to '9' clearly indicates this. - Igor
  • @Igor, and shouldn't the same ones and zeros be, but as numbers, not characters? (In the original order) - Elvin
  • Did not understand the last comment. - Igor
  • @Igor, will this not fix the situation? num2and1 [i]> = '0' && num2and1 [i] <= '1' - Elvin
  • The code you gave transforms (tries to convert) the string with the number "one hundred ten billion one hundred ten thousand one" to an integer. The number, of course, does not fit into the int , wraps itself around the maximum value many times and results in garbage. - Igor

2 answers 2

First, the code for translating the record of the number into the number itself is given to translate from the decimal record. And you obviously want to translate from binary . For translation from binary , it will look something like this.

 const char *num2and1 = "110000110001"; long n = 0; for (unsigned i = 0; num2and1[i] >= '0' && num2and1[i] <= '1'; ++i) n = 2 * n + (num2and1[i] - '0'); printf("%ld", n); 

Secondly, there is no point in writing all this out by hand when there is a ready-made translation function for strtol in the standard library.

 const char *num2and1 = "110000110001"; long n = strtol(num2and1, NULL, 2); printf("%ld", n); 

To print a value of type long need the %ld format specifier, not %d .

Thirdly, what is "and from it already in the ASCII character" is not clear. In this example, the binary entry corresponds to the number 3121 . Where is the "ASCII character"?

  • and what NULL does in strtol - Elvin
  • @Elvin: It tells the strtol function that you do not want to know where in the line the translation process stopped. - AnT
  • 3121. Where is the "ASCII character" the same unit - Elvin
  • "same unit" ??? Nothing is clear. - AnT
  • printf ("% c", 3121); displays the unit - Elvin

You yourself say that this is a binary number. Then it is necessary to multiply by 2:

 n = 2 * n + (num2and1[i] - '0'); 

And so you want to write a 12-digit number into the int type, and you get an overflow - hence the negative value ...