Convert string of 1/0's to binary

I want to send in a list of binary numbers via the Particle.function argument; so something like ā€œ101010111111111ā€ and convert it to a byte (or integer = 22015) so that when I send it to a function that writes the bytes to an i2c device, it gets the bits in that order.

There must be a quick way to do this?


@marcusone, take a look at the C-string function strtol():smile:



bah, thanks @peekay123 I should have read further down on that function to see that you could set the base ā€˜2ā€™ on it! I just assumed it would do things like ā€˜123ā€™ up to a long int :blush:

1 Like

@peekay123 iā€™m having an issue

char buf[16];
args.toCharArray(buf, 16);
uint16_t ps = strtol(buf, NULL, 2);
Serial.println(ps, BIN);

When i send in ā€˜1111111111111111ā€™ (16 ones),
the output is 15 ones, not 16!

any ideas why?


Your array also has to include the terminating NULL so size needs to be one larger. :wink:

Thanks! had to increase both the buffer and the toCharArray to 17 did the trick.
I had tried the buffer, but forgot to up the number in the function :wink:

1 Like