I pass an array to the function:

char *buffer 

it stores numbers in decimal notation. It is necessary to translate them into int . The numbers inside - from 0 to 255. The first question is: how to translate each element of a given array into a number in the decimal SI? The second question: there is a function for converting from the 10th SI to the binary one:

  void getBin(int num, char *str, int *cnt) { int mask = 0x10 << 1; *(str + 8) = '\0'; while (mask >>= 1) { *str++ = !!(mask & num) + '0'; *(cnt)++; } } 

Call this function like this:

 getBin(number, buf. &counter); 

where number is the number in decimal notation ( int ); buf - char pointer, in which the result will be written; counter is the int variable that I need to count iterations in a function.

For some reason, after a call to counter 0 is stored, and in the buf not what I need .. Help, please, sort it out.

  • You clearly have some terminological confusion ... - Harry
  • Tell me what? - Setplus
  • one
    For example, what does it mean that buffer stores numbers in decimal notation? This means 1) that each char is treated as a number, 2) that one number is written there as a string, 3) that several numbers are written there as a string? 1 pushes the fact that there are a lot of numbers and they are from 1 to 255. On 2 or 3 - that they are in decimal notation - well, what can a binary representation have in the memory? And so almost everywhere ... - Harry
  • one
    Give a few examples of input and output - Andrio Skur
  • 1. I will explain more specifically: I read the file as an array of bytes in char * . Now in each memory cell there are stored numbers from 0 to 255. As for the example of the input data, I tried to access the array elements as buffer[i] - '0' , so that they could be converted to int numbers, but it did not help. Therefore, I think how best to do it. - Setplus

1 answer 1

I will write a working code, and give my opinion.

First, I don’t understand at all why to write this:

 *str++ = !!(mask & num) + '0'; *(cnt)++; 

Those. Here, the complex structure of the code, so it also does not work in addition. And you did not come to the idea of ​​trying to simplify and write linearly, without a heap of operations in 1 line. And asked for help here. I just find it extremely incomprehensible why it is so critical to preserve just such a structure of code, and why YOU are confident that you did not get confused in it. And you are confused and wrong.

So, answering the question:

The first error in the line *(cnt)++; . Replace with *cnt += 1; and everything starts to count. Again, as an option, simply (*cnt)++; . The meaning does not change.

The second error in the line is int mask = 0x10 << 1; . Change to int mask = 1 << 8; and everything becomes correct. Also, if the author is fundamentally, then int mask = 0x10 << 3; We go into any calculator, with the possibility of left-shift operation, and 16-bit system and everything becomes obvious.