Converting String or Integer to byte array

Okay, I have a API call that is sending the Arduino a 4 digit number as a string (from the sending side) as part of a randomizing action. I need to convert this to a byte though for the program to work.
Input: String 4231
Output: byte {4, 2, 3, 1}

Does this make sense?

Not sure how to accomplish this.

EDIT - fix hex values
Do you want the bytes to be the binary versions of the string characters or to just separate the characters in the string. For example do you want the first byte to be hex 04 or hex 34?

I had a similar question. If he wants the '4' to be 0x04, then if the numbers are in the range '0' to '9', just subtract '0'. Like this:

char ch=0x50 // '2'
char outch=0;

if((ch<='9')&&(ch>='0')) {outch=ch-'0';}

There is no error or array handling in that code, but it's the core I use for parsing numbers.

  • Wes

or, do you want the string 4231 to become a single number, 4231, as in four thousand, two hundred and thirty one? That is another possible interpretation of your question. afterall, you said

"4 digit number"

Well I figured it out. In my case, since I could already send it as a String, I used substring to get the individual digits with .toInt() to convert from String to int. Then manually saved the array calling each slot in the array and saving each location to that position

void apiGameOrder(String receivedOrder) {
  Serial.print("Solve Order received: ");
  Serial.println(receivedOrder);

  ones = receivedOrder.substring(0,1);
  tens = receivedOrder.substring(1,2);
  hund = receivedOrder.substring(2,3);
  thou = receivedOrder.substring(3,4);
  order[0] = ones.toInt();
  order[1] = tens.toInt();
  order[2] = hund.toInt();
  order[3] = thou.toInt();
}
1 Like

substring is relatively "heavy". It has to allocate memory for a whole new String. Use [] element access to get each character and then convert it to a byte value:

void apiGameOrder(const String& receivedOrder) {
  for (int i = 0; i < 4; ++i) {
    order[i] = receivedOrder[i] - '0';
  }
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.