Converting from int to byte array then back to int using atoi and itoa on Arduino for transmission

StackOverflow https://stackoverflow.com/questions/15764247

  •  31-03-2022
  •  | 
  •  

문제

I am converting an signed int to send over Arduino Wire as multiple bytes so I did the following:

The code below is the debugging of my implementation, you can copy into the Arduino IDE to see printout.

What I cant understand is how itoa creates an array larger than the declared size which is not detectable by sizeof(). My declared array was size 2 but itoa used an array of size 6 to store its result!!

Serial.println("|----START DEBUG------|");
int Sensor1Data=-32760;
Serial.print("Sensor1Data: ");Serial.println(Sensor1Data);
byte Sensor1CharMsg[2];

Serial.println("|----STAGE 2------|");
Serial.print("Array Size b4 itoa: ");Serial.println(sizeof(Sensor1CharMsg));
itoa(Sensor1Data,(char*)Sensor1CharMsg,10);
Serial.print("Array Values up to 10 elements: ");Serial.write(Sensor1CharMsg,10); Serial.println("");
Serial.print("Array Size a4tr itoa: ");Serial.println(sizeof(Sensor1CharMsg));

Serial.println("||||||| ARRAY OUTPUT|||||||");
Serial.print("Sensor1CharMsg[0]): ");  Serial.println(Sensor1CharMsg[0]);
Serial.print("Sensor1CharMsg[1]): ");  Serial.println(Sensor1CharMsg[1]);
Serial.print("Sensor1CharMsg[2]): ");  Serial.println(Sensor1CharMsg[2]);
Serial.print("Sensor1CharMsg[3]): ");  Serial.println(Sensor1CharMsg[3]);
Serial.print("Sensor1CharMsg[4]): ");  Serial.println(Sensor1CharMsg[4]);
Serial.print("Sensor1CharMsg[5]): ");  Serial.println(Sensor1CharMsg[5]);
Serial.println("|||||||END ARRAY OUTPUT|||||||");

After transmission:

int Sensor2Data = atoi((char*)Sensor1CharMsg);
Serial.print("Sensor2Data: ");Serial.println(Sensor2Data);

Result

|----START DEBUG------|
Sensor1Data: -32760
|----STAGE 2------|
Array Size b4 itoa: 2
-32760
Array Size a4tr itoa: 2
||||||| ARRAY OUTPUT|||||||
Sensor1CharMsg[0]): 45
Sensor1CharMsg[1]): 51
Sensor1CharMsg[2]): 50
Sensor1CharMsg[3]): 55
Sensor1CharMsg[4]): 54
Sensor1CharMsg[5]): 48
|||||||END ARRAY OUTPUT|||||||

After Transmission

Sensor2Data: -32760
도움이 되었습니까?

해결책

You are overwriting memory, invoking undefined behavior.

Also, itoa() doesn't exactly create a "byte array", it creates a string. The name means "integer to ASCII". The documentation says:

The caller is responsible for providing sufficient storage [...]

Finally, a string's length is computed by strlen(), not by sizeof.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top