# Arduino: String to char Array

I get a String like: XXXXXXXXX

Its length is fixed and 9.

I need to get an char array like:

char array[9] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};


... from there on my sketch processes this array.

Maybe someone has an idea on how to achieve this. I thought about a for-statement to store every single letter in a string array. Then another for-statement to build an char array with the hex presentation of each string. Seems to be a bit complicated though I think.

EDIT:

What I need to do:

1. Separate the string into letters / figures.
2. Change every single letter to its HEX representation.
3. Build a char Array out of the HEX values.

Example:

1. 123 (String)
2. 0x310x320x33 (String or whatever ...)
3. {0x31,0x32,0x33} (Char-Array)

This is what I need!

Sounds like the following string.toCharArray(buf, len) is what you want. as exampled

String stringOne = "123456789";
char charBuf[50];
stringOne.toCharArray(charBuf, 50) ;
Serial.println(stringOne);
for (int i = 0; i < 9; i++) {
Serial.print(" 0x");
Serial.print(charBuf[i], HEX);
}
Serial.println();


yields:

123456789
0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39


as each contents of charBuf is an uint8_t, regardless of how it is printed.

Unless you are asking for each element of the array to be another string of the ASCII representation of the HEX. or are you asking to have a char array of "0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39"

• Already used that. The point is, that the Array then looks like {0x00,0x00, ... , X,X,X,X,X,X}, so the string is not converted to HEX. P.S. I have a static char (HEX) array in front of my I need to convert the string to HEX-Array – DAS Feb 8 '13 at 15:28
• I edited my question. – DAS Feb 8 '13 at 15:36
• @Darwin string.toCharArray will do exactly what your example shows. – George Feb 8 '13 at 15:41
• keep in mind that char array is an array of integers. Not HEX nor DEC. – mpflaga Feb 8 '13 at 15:47
• Well ... you are right. My project now works, did not expect that for today. Thanks a lot! Made things a lot easier! – DAS Feb 8 '13 at 16:06

If your string variable is of Arduino type String, you can use a toCharArray() method to get an array of chars.

char array[9];
yourString.toCharArray(array, 9);

• Maybe my question was not precise ... I have a String. The string must be separated into a array. Each child of the array must be converted to HEX. – DAS Feb 8 '13 at 15:31
• hex is just a representation of a number. If you want them output in hex, use HEX argument in call to Serial.print. Like so: Serial.print(array[i], HEX) – miceuz Feb 8 '13 at 17:02

If You Have String

String item= "Hello";

AUX3= item.charAt(0);

AUX3 is 0x48 in Hex, 72 in Dec

 if (AUX3==72) {