Convert binary format string to int, in C

前端 未结 7 604
刺人心
刺人心 2020-12-01 21:21

How do I convert a binary string like \"010011101\" to an int, and how do I convert an int, like 5, to a string \"101\" in C?

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 21:54

    If it is a homework problem they probably want you to implement strtol, you would have a loop something like this:

    char* start = &binaryCharArray[0];
    int total = 0;
    while (*start)
    {
     total *= 2;
     if (*start++ == '1') total += 1;
    }
    

    If you wanted to get fancy you could use these in the loop:

       total <<= 1;
       if (*start++ == '1') total^=1;
    

提交回复
热议问题