String to byteArray in Arduino

ArduinoHardwareSoftware & Coding

The getBytes() function helps copy the content of a String to a byte array. The syntax is −

string1.getBytes(buf,len)

where,

  • string1 is the string whose content you want to copy to a byte array,

  • buf is the byte array, and

  • len is the length of content to be copied.

Example

The following example illustrates how to use this function −

byte buf[10];
void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   s1.getBytes(buf, 5);
   for (int i = 0; i < 10; i++) {
      Serial.println(buf[i]);
   }
}
void loop() {
}

Output

The Serial Monitor output is shown below −

As you can see, the characters have been copied into the byte array. 72 corresponds to the decimal value of 'H' as per the ASCII code, 101 corresponds to the decimal value of 'e' and so on.

Note that, although the value for len was specified as 5, the bytes of only 4 characters were copied. This indicates that the last byte is intentionally kept as 0 to indicate string termination. You can try setting other values for len, and you'll get a similar result. The last byte will be kept as 0.

raja
Published on 24-Jul-2021 14:07:44
Advertisements