Converting binary strings to bytes/integers?

Hi everyone! I've been searching everywhere for the answer to what I think may be a basic question, but I really cannot find anything on how to convert a binary string to a byte/integer.

Essentially I want to do this:

String "0100 1010" --> converted to int 74... (preferably in as little steps as possible)

any ideas?

in code

char s[] = "01001011";
int value = 0;
for (int i=0; i< strlen(s); i++)  // for every character in the string  strlen(s) returns the length of a char array
{
  value *= 2; // double the result so far
  if (s[i] == '1') value++;  //add 1 if needed
}
Serial.println(value);

That works great, thanks! :slight_smile:

Just one more thing though, how would I be able to feed in a string variable if I needed to?

In fact no worries, I've sorted it!
For anyone interested:

String data = "0110 1101" //string to be used
   char s[8];
   data.toCharArray(s, 8);

   //Then just use the rest of the code given in the post above ^^

Hope this helps guys! XD

To avoid the copying of data, you can use the string data directly:

char *s = &data[ 0 ];

I would like to recommend checking the AVR C-Lib when in need. There a tons of standard C functions ready to be used. The above problem can be solved with a single function call.

int value = strtol(data, (char**) NULL, 2);

http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaf8ce3b8dae3d45c34c3b172de503f7b3
Arduino is NOT a programming language. It is a set of function implemented in C and partly C++.

Also I would recommend avoiding the Arduino String class as this often leads to "the dark side". The standard C string functions are more efficient and does not hide memory issues.

Cheers!