简体   繁体   中英

How to convert a specific element of a String into an int Arduino/C++

I was working on a converter project using Arduino/C. At a certain point in my code, a String sequence of 0's and 1's is generated, as an example: my_string = "01101"; . I want to process this data in a for loop like shown in this minimal example:

String x = "01011", y = "00011"; // These variables necessarily must have the same length

for(int i = 5; i > -1; i--) // Going from last index to first
{
    bitsum = x[i].toInt() + y[i].toInt(); // Summing up each pair of bit, here is the problem
}

My point is: is there a way to take an exact and specific element of the String and convert it to int one by one?
Thanks in advance!

If you are sure that the characters of my_string will always be numerals, then the typical method of obtaining a char numeral's numeric value is by just subtracting '0' . This works because the ASCII values for the numerals are arranged in order, so by subtracting '0' , you're subtracting their offset (48) from the actual 0 value.

The charAt(n) method can be used to get the character at a given index.

bitsum = x.charAt(i) - '0' + y.charAt(i) - '0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM