2016/10/03

Arduino - Getting the ASCII code of character or string

Here is an example of how to get the ASCII code of a character or a string.

Code




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void setup() {
 Serial.begin(9600);
 char string[] = "A string of ASCII Characters";
 char buffer[4*sizeof(string)]; //sized for the worst case scenario of each being in the hundreds plus a space between each and a null
 char* buffPtr = buffer;

 Serial.print("The string to be converted: ");
 Serial.println(string);
 
 for(byte i = 0; i < sizeof(string) - 1; i++){
   
   itoa((int)string[i],buffPtr,10); //convert the next character to a string and store it in the buffer

   Serial.print(string[i]);
   Serial.print(' ');
   Serial.println(buffPtr);
   
   buffPtr += strlen(buffPtr); //move on to the position of the null character
   *buffPtr = ' '; //replace with a space
   buffPtr++; //move on ready for next
   
 }
 buffPtr--; //move back a character to where the final space (' ') is
 *buffPtr = '\0'; //replace it with a null to terminate the string
 //Serial.println();
 Serial.println(buffer);
}

void loop() {
  // put your main code here, to run repeatedly:
}

Output



Reference:

Topic: How to get Ascii of character or string ?
https://forum.arduino.cc/index.php?topic=125855.0

No comments:

Post a Comment