Reputation: 45
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 :)
Upvotes: 1
Views: 1281
Reputation: 399871
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;
}
Upvotes: 2
Reputation: 53006
You need to change this
int sign[8]= {0,1,0,1,0,1,1,1};
to
char sign[9]= {'0','1','0','1','0','1','1','1','\0'};
the way you had it you was using the ascii value 1
instead if the character '1'
, and you should add a null terminating byte '\0'
so the array can be used as a string.
And then, you can
char c = (char) strtol(sign, NULL, 2);
printf("%c\n", c);
Upvotes: 2