Search code examples
cstringintstrtol

Int array to string for strtol


I want to get

int sign[8]= {0,1,0,1,0,1,1,1};        

to use on strtol function like

char c = (char) strtol(sign, NULL, 2);
printf("%c\n", c);

I have no idea how to cast sign to use in strol. When I'm using

 c = (char) strtol("01010111", NULL, 2);

everything is ok and I want to get such result.

Please help :)


Solution

  • The problem is that sign is not a string, it's an array of small integers.

    You can interpret them directly as bits and convert the array into a number, there's no point in going via strtol() (and, in fact, it's rather un-idiomatic in C to do it your way).

    Just loop:

    unsigned int array_to_int(const int *bits, size_t num_bits)
    {
      unsigned int ret = 0, value = 1;
      for(; num_bits > 0; --num_bits, value *= 2)
        ret += value * bits[num_bits - 1];
      return ret;
    }