8

I have got a String filled up with 0 and 1 and would like to get an Integer out of it:

String bitString = ""; 
int Number;
int tmp;
bitString = "";
 for (i=1;i<=10;i++)
 {
 tmp= analogRead (A0);
 bitString += tmp % 2;
 delay(50);
 }
// now bitString contains for example "10100110" 
// Number = bitstring to int <-------------
// In the end I want that the variable Number contains the integer 166
asked May 12, 2014 at 18:31
4
  • What is the question? What do you expect this code to do and what is it doing? What else have you tried? Commented May 12, 2014 at 18:42
  • @Craig I eddited the question. For example If the bitString contains a "10100110" I want the programm to save it as the decimal 166 in the int variable. Commented May 12, 2014 at 18:46
  • Do you need the string? You could create the integer representation directly. Commented May 12, 2014 at 19:14
  • @Craig i would also like to print out the bitstring Commented May 12, 2014 at 19:15

2 Answers 2

6

If you only need the string for printing you can store value in an integer and then use the Serial.print(number,BIN) function to format the output as a binary value. Appending integers to strings is a potentially costly operation both in performance and memory usage.

int Number = 0;
int tmp;
for (int i=9;i>=0;i--) {
 tmp = analogRead (A0);
 Number += (tmp % 2) << i;
 delay(50);
}
Serial.print(Number, BIN);
answered May 12, 2014 at 19:33
1
  • Yes your solution looks more efficient! and does the work Commented May 12, 2014 at 19:36
5

Check out strtoul()

It should work something like this:

unsigned long result = strtoul(bitstring.c_str(), NULL, 2);

Now you have a long variable which can be converted into an int if needed.

answered May 12, 2014 at 19:14
2
  • @kimliv Did you add .c_str() to the end of bitstring as Peter pointed out above? c_str() should return a const char*. Commented May 12, 2014 at 19:22
  • it is working that way! Commented May 12, 2014 at 19:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.