There is an array:

byte customChar[8] = { B00000, B00000, B00000, B00000, B00000, B00000, B00000, B00000 }; 

In one of the functions, I collect a string like "10101" . Is there a function or method for converting this string to mind B10101 to add as an element to the customChar array?

  • Need to convert the string "10101" to the number b10101? You can try stoi , for example: byte b = (byte) std::stoi("10101", nullptr, 2); - gil9red
  • The value of the form B10101 is some kind of extension arduino, apparently. There are no such literals in b10101 , so converting a string to a number of the type b10101 to add to the array looks meaningless. Yes, and the addition to the array of this type in runtime is not possible. The size of the array is fixed at compile time, you can only change the available values. - αλεχολυτ
  • @ älёxölüt, so I don’t need to add, but just change a certain element of the array (which is specified above), that is, there was an element B00000-> when the function was working, we got the string "10001" -> changed the element of the array to value B10001 - MaNa
  • @ gil9red, gives the error 'stoi' is not a member of 'std' and 'nullptr' nov
  • In order for stoi be, you need to have C ++ 11 support. Is it in your compiler? Or you can use strtol . - αλεχολυτ

2 answers 2

To convert the number specified by the string to a specific numeric value, you can use functions like std::stoi or std::strtol , where you also need to specify the number system, in the current case, this is 2 . The first function requires the support of the C ++ 11 standard, the second will work without it:

 #include <cstdlib> byte value = static_cast<byte>(std::strtol("10001", NULL, 2)); 

After conversion, you can write the value to the desired cell in the array:

 customChar[index] = value; 
     typedef unsigned char bin_t; void binToString(bin_t number, char *result) { result[0] = 'B'; for( bin_t n = sizeof(bin_t); n > 0; --n) { result[sizeof(bin_t) - n + 1] = (number & (1 << (n - 1))) ? '1' : '0'; } result[sizeof(bin_t) + 1] = 0; } ... char str[sizeof(bin_t)+2]; bin_t number = 0b0101001; binToString(number, str); std::cout << str;