Hi, I need to convert a string to another string but in hexadecimal representation, I am using this code to do it but I only manage to convert the first character of the string, what could be my error?
char msgArray[] = "example message";
char HexString[20];
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println(msgArray);
for (int i = 0; i < sizeof(msgArray) - 1; i++) {
sprintf(HexString, "%02x", msgArray[i]);
}
Serial.println();
for (int i = 0; i < sizeof(HexString) - 1; i++) {
Serial.print(HexString[i]);
}
Serial.println();
}
void loop(){
}
You continually write different values to the same buffer, and don't print it. Oops that was already mentioned... so print it as you go along. There is no need to accumulate characters in a print string as they will be printed consecutively anyway...
it's only needed if you are saving it for some other purpose, that you would need to construct a string containing all the values.
As @AWOL says, you are overwriting HexString each time you convert a character. Use sprintf() and strcat() together. Also as he says, the HexString is not sized for all the converted characters.
char msgArray[] = "example message";
//char HexString[20];
char HexString[sizeof(msgArray) * 2 + 1]; //2 nibbles/byte + null terminator
char tempChars[3];//2 nibbles/byte + null terminator
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println(msgArray);
for (int i = 0; i < sizeof(msgArray) - 1; i++) {
//sprintf(HexString, "%02x", msgArray[i]);
sprintf(tempChars, "%02x", msgArray[i]);//hex string with two nibbles
strncat(HexString, tempChars, 2);//append 2 chars
}
Serial.println();
for (int i = 0; i < sizeof(HexString) - 1; i++) {
Serial.print(HexString[i]);
}
Serial.println();
}
void loop(){
}