If I understand your question correctly, your task is to write a function which takes as input a string and two int
arguments representing a range of bits, and this function should return an int
representing the value of this range, when interpreting the individual characters as bits.
If your string is not so long that the whole binary number won't fit into a long int
(i.e. the whole number is not larger than LONG_MAX
, which must be at least 4,294,967,295
, which corresponds to 32 bits), then you can use the function strtol
to read in the whole number. You can then mask out all the bits that you are not interested in, by using the bitwise-AND operator &
. Also, if the range does not start at 0
, then you should use the bit-shift operator >>
to move all bits by that number.
On the other hand, maybe you are not supposed to use the function strtol
to solve this problem. I cannot tell, because you did not mention any such restriction in the question, and in the comments section, you stated that you simply wanted the easiest solution. If you are not supposed to use this function, then you are probably supposed read the individual bits of the string in a loop, and use the loop to go through the desired range of the bits. For every bit you encounter that is set (i.e. equals 1
), you can then add the number 1
, bit-shifted by an appropriate amount, to the result.
In accordance with the community guidelines on homework questions, I will not provide the full solution to your problem at this time. However, I can add code later, if required.