String To ByteArray In Arduino - Tutorialspoint

  • Home
  • Whiteboard
  • Online Compilers
  • Practice
  • Articles
  • AI Assistant
  • Jobs
  • Tools
  • Corporate Training
  • Courses
  • Certifications
Menu Categories Login
  • Switch theme
  • SQL
  • HTML
  • CSS
  • Javascript
  • Python
  • Java
  • C
  • C++
  • PHP
  • Scala
  • C#
  • Tailwind CSS
  • Node.js
  • MySQL
  • MongoDB
  • PL/SQL
  • Swift
  • Bootstrap
  • R
  • Machine Learning
  • Blockchain
  • Angular
  • React Native
  • Computer Fundamentals
  • Compiler Design
  • Operating System
  • Data Structure and Algorithms
  • Computer Network
  • DBMS
  • Excel
Technical Questions and Answers
  • Data Structure Data Structure
  • Networking Networking
  • RDBMS RDBMS
  • Operating System Operating System
  • Java Java
  • MS Excel MS Excel
  • iOS iOS
  • HTML HTML
  • CSS CSS
  • Android Android
  • Python Python
  • C Programming C Programming
  • C++ C++
  • C# C#
  • MongoDB MongoDB
  • MySQL MySQL
  • Javascript Javascript
  • PHP PHP
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who
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.

Yash Sanghvi Yash Sanghvi Updated on: 2021-07-24T14:07:44+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started Print Page Previous Next Advertisements

Tag » Arduino Write Byte Array