Search code examples
arduinobinaryarduino-uno

Is it possible to parse a String into a Binary value?


Hi and thanks in advance for any answers.

I wanted to know if there is a way to convert a string (for example str = "B10010"), to the same binary value (eg. int = B10010).

I wanna clarify that I wanna do this because it would be way easier to go back and forth between a charArray and string to change the one digit in the binary value, so if there is a better to do that (and I feel like there should be) I would love to know :)


Solution

  • To convert a string to a binary:

    byte getByteFromString(char* str){
        // Don't accept strings less than 8 long
        if(strlen(str) < 8) return;
        byte retval;
        for (int i=0; i<8; i++){
           // shift over what's there
           retval = retval << 1;
           if(str[i] == 1){
              retval |= 1;
           }
        }
        return retval;
    }
      
    

    That answers your question, but I also saw this: I wanna clarify that I wanna do this because it would be way easier to go back and forth between a charArray and string to change the one digit in the binary value, so if there is a better to do that (and I feel like there should be) I would love to know :)

    and I have to say no, this is a crazy way to do it. It is WAY easier to just work with binary values.

    To set a bit in a binary value, OR with a byte with only that bit.

    if bit is 0-7 marking the bit you want to set

    value = value | (1 << bit);
    

    To clear a bit, AND with a byte with only that bit cleared

    value = value & ~(1<<bit);
    

    Here is some more to read: https://docs.arduino.cc/learn/programming/bit-math