优化转换功能(字符串到字节)

时间:2019-03-04 13:21:13

标签: arduino

您好,我正在与arduino一起编写程序。我写了一个将字节转换为字符串的函数,但是它占用了很多内存。我的问题是,是否有我可以使用的功能,并且它在我的arduino上没有占用太多内存。 我在下面发布代码。

byte strConv(String str)
{
  byte a = 0;
  char n = 2;
  char g = 3;
  char stringa1;
  char stringa2;

  char m;

  stringa1 = str.charAt(n);
  stringa2 = str.charAt(g);

  m = costanti (stringa1);

  if (m >= '0' && m <= '9'  || m >= 'A' && m <= 'F') {
    a += m;
  } else {
    a += m;
  }
  a = a << 4;
  m = 0;
  m = costanti (stringa2);
  if (m >= '0' && m <= '9' || m >= 'A' && m <= 'F') {
    a += m;
  } else {
    a += m;
  }
  return a;
}

和第二个功能:

char costanti(char n) {

  char num;

  switch (n) {

    case '0':
      num = 0;
      break;

    case '1':
      num = 1;
      break;

    case '2':
      num = 2;
      break;

    case '3':
      num = 3;
      break;

    case '4':
      num = 4;
      break;

    case '5':
      num = 5;
      break;

    case '6':
      num = 6;
      break;

    case '7':
      num = 7;
      break;

    case '8':
      num = 8;
      break;

    case '9':
      num = 9;
      break;

    case 'A':
      num = 10;
      break;

    case 'B':
      num = 11;
      break;

    case 'C':
      num = 12;
      break;

    case 'D':
      num = 13;
      break;

    case 'E':
      num = 14;
      break;

    case 'F':
      num = 15;
      break;
  }
  return num;
}

我可以在新的优化功能中减少这两个功能吗?

1 个答案:

答案 0 :(得分:1)

据我了解,您想要这样的东西:

char strConv(String str)
{
  if(str.length() > 2)
    return -1; // return something which makes sense to you for "invalid"
  return static_cast<char>(strtol(str.c_str(), NULL, 16));
}

String myString(26, HEX); // creates the string "1A" for you

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("String: \""+myString+'"');
  char val = strConv(myString); //gives you the 26 again
  Serial.print("int: ");
  Serial.println(static_cast<int>(val));
  delay(1000);
}

这会提示我以下内容:

String: "1a"
int: 26
String: "1a"
int: 26
...