Char to bytes conversion function

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

Hello

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;
}
2 Likes

Thank you for your answer. However using it the total i get is 146 instead of 92. It seems i have subtract 18 from each?

Because 146 in decimal is 92 in hex

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);

Thank you for reply. I think i understand the problem better but i still cannot put it together.

Your code gives me invalid conversion from 'char' to 'const char*'

Which line is having the error? See updated above - I have corrected it where I think it could be.

Sorry I should have mentioned that I have not compiled or tested that code - its just written in the forum editor.

the row

sum += (unsigned char)atoi(myString[i]);

gives me the error

invalid conversion from 'char' to 'const char*' [-fpermissive]

Ah, i miscalculated... @guix your solution was the correct one. Thank you both for help!

Got it. I have updated the code above - still untested.

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