Go Down

Topic: Converting String to binary code (Read 8799 times) previous topic - next topic


Hey there,

I would like to convert a String to a String of binary code at runtime.


String myText = "Hello World";
String binaryText = "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100";

Unfortunately I don't have a clue how to do it.
Can somebody help me?

Thank You!


a clue only:

Code: [Select]
byte *p = myText;
while (*p != 0)  { Serial.print(*p, BIN); p++; }


"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.


You can do it like this.  In my sketch the least significant bits of each character are printed first, so the output will look a little different than what you posted.  Is that OK?

Code: [Select]
// Text to binary using serial monitor input
// Tom Fangrow, August 10, 2012

void setup() {
  Serial.begin(9600);         // open serial port at 9600 baud

void loop() {
  if(Serial.available()) {    // if anything on port
    byte c = Serial.read();   // read one character
    for(int i=0; i<8; i++) { 
      Serial.print(c%2);      // print the least significant bit
      c /= 2;                 // move to next significant bit


Thank you all for the reply!   :)

This is my solution:

Code: [Select]

String myText = "Hello World";

for(int i=0; i<myText.length(); i++){

   char myChar = myText.charAt(i);
    for(int i=7; i>=0; i--){
      byte bytes = bitRead(myChar,i);
      Serial.print(bytes, BIN);


Go Up