Problems with String Concatenation

Hi,

I’ve been having serious issues with string concatenation. Here is my code:

String hexToBinary(String hex) {
  String binary = "";
  if (hex.length() % 2 == 0) {
    for (uint8_t i = 0; i < hex.length(); i++) {
      if (hex.charAt(i) == '0') { 
        binary.concat("0000"); }
      else if (hex.charAt(i) == '1') {
        binary.concat("0001"); }
      else if (hex.charAt(i) == '2') {
        binary.concat("0010"); }
      else if (hex.charAt(i) == '3') {
        binary.concat("0011"); }
      else if (hex.charAt(i) == '4') {
        binary.concat("0100"); }
      else if (hex.charAt(i) == '5') {
        binary.concat("0101"); }
      else if (hex.charAt(i) == '6') {
        binary.concat("0110"); }
      else if (hex.charAt(i) == '7') {
        binary.concat("0111"); }
      else if (hex.charAt(i) == '8') {
        binary.concat("1000"); }
      else if (hex.charAt(i) == '9') {
        binary.concat("1001"); }
      else if (hex.charAt(i) == 'a') {
        binary.concat("1010"); }
      else if (hex.charAt(i) == 'b') {
        binary.concat("1011"); }
      else if (hex.charAt(i) == 'c') {
        binary.concat("1100"); }
      else if (hex.charAt(i) == 'd') {
        binary.concat("1101"); }
      else if (hex.charAt(i) == 'e') {
        binary.concat("1110"); }
      else if (hex.charAt(i) == 'f') {
        binary.concat("1111"); }
      Serial.println(hex.charAt(i));
    }
    return binary;
  }
  else {
    Serial.println("Error: Failed to convert hex to binary (uneven or incorrect hex format)");
    return "00000000";
  }
}

I’ve already tried using +'s instead of concat() and that didn’t seem to make any difference. It seems if I input a large string into the function, the string concat stops working and I end up getting a return of a segment of what should be there. It works normally with shorter string inputs. Please let me know if I’m doing something wrong here!

Thanks,
Levi

Please let me know if I'm doing something wrong here!

Yes, you're using the String class. That class is made for PC with memory management units and lots of RAM. The UNO has 2kB of RAM and the String class fragments that little memory in no time if used extensively as you're doing it. A rather efficient way to deal with strings is using C-strings (character arrays) but even better is to avoid having large strings and parsing or putting out the strings while you're constructing them.