Convert binary format string to int, in C

前端 未结 7 592
刺人心
刺人心 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 22:11

    The strtol function in the standard library takes a "base" parameter, which in this case would be 2.

    int fromBinary(const char *s) {
      return (int) strtol(s, NULL, 2);
    }
    

    (first C code I've written in about 8 years :-)

提交回复
热议问题