Hi. For the last few hours im trying to convert char to byte and then sum all the bytes.
For example
char* data = "101";
byte countBytes(char* data) {
int total;
for (byte i = 0; i < sizeof(data) ; i++) {
Serial.println(data[i],HEX);
total =total +??? // cant figure this out
}
return total;
}
The println is returning the right values but i can't seem to get them in var. I was trying to use atoi without sccess The desired result for this function is 92 (31+30+31). I know i missing something silly but for the love of god cant seem to find the solution
In this context, sizeof(data) will return 2, the size of a char pointer, not the size of the pointed array. You have to add another parameter length to the function, this is the only way the function can know the length of the array
Or, as it it a c-string (a null-terminated char array), you can detect the end of the array when the character is 0
Also, total should be initialized to 0. You always have to initialize local variables if you care about their initial value.
And the return type of the function should be the same type as the returned value
Try something like this
int countBytes( const char * data )
{
int total = 0;
const char * p = data;
while ( *p != '\0' )
{
total += *p++;
}
return total;
}
If my basics are still good, char to byte in C is basically casting 'char' to 'unsigned char', though both take up 8-bits (i.e. a byte). For example (will crash if non-numeric characters such as symbols appear in the string):
char *myString = (char *)"12345";
//This should work as well...
//char myString[] = "12345";
unsigned char sum = 0;
for (int i = 0; i < strlen(myString); i++)
{
char *tmp = new char[2];
tmp[0] = myString[i];
tmp[1] = '\0';
sum += (unsigned char)atoi(tmp);
delete[] tmp; //Check if delete[] is correct, or it is just delete
}
printf("Sum = %d", sum);