Converting bytes to char, to string and to int

Hi, I didn't find an answer to my issue, so I decided to ask here.

I have this:

byte receivedBytes[30];
receivedBytes[0] = 48;
receivedBytes[1] = 48;
receivedBytes[2] = 49;

Now, I need to convert these 3 bytes to its numeric value, so I did it this way:

String tmp = String((char)receivedBytes[0]) + String((char)receivedBytes[1]) + String((char)receivedBytes[2]);
byte bt = tmp.toInt();

The input is 001 in bytes, and the output is 1 (numeric value of 3 bytes concatenated).
This is working, but what I want to know is: is there a better way (or best practices) to do this?
Thank you

byte receivedBytes[30];
receivedBytes[0] = 48;
receivedBytes[1] = 48;
receivedBytes[2] = 49;
receivedBytes[2] = 0;
int x = atoi ((const char*)receivedBytes);

umm, this:
receivedBytes[2] = 0;
should probably have been
receivedBytes[3] = 0;
or were you testing our new member?
C

Yup, my bad - cut-and-paste error.

Another way if you don't have the option to add a terminating null character.

  int x = receivedBytes[0] - '0';
  x += (receivedBytes[1] - '0') * 10;
  x += (receivedBytes[2] - '0') * 100;
  Serial.println(x);

Note that the way in which you use String (capital S) concatenation might bite you in the future.

Another way if you don't have the option of using atoi() function. add a terminating null character.

Your buffer is 30 bytes long, but you're receiving characters and then deciding they're all received, "somehow", so at that point, put the terminating \0 at the last location and do atoi(). Actually showing us your whole code would have been beneficial.
C

adding the null character opens up to more solution than atoi(). strtol() for example or sscanf()

Another way if you don't have the option to add a terminating null character (at the expense of adding a large function to your code):

➜ you could also actually use sscanf() without adding the null char by limiting the field width to 3

this code will print 123 and not 12345

char buffer[] = "12345";

void setup() {
  Serial.begin(115200);
  int v =0;
  sscanf(buffer, "%3d", &v);
  Serial.print("I read : "); Serial.println(v);
}

void loop() {}

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