Go Down

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

#### foxyNik

##### Aug 10, 2012, 01:15 pm
Hey there,

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

Like:

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

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

Thank You!

#### michael_x

#1
##### Aug 10, 2012, 01:46 pm
a clue only:

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

#### AWOL

#2
##### Aug 10, 2012, 02:01 pm
"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.

#### JavaMan

#3
##### Aug 10, 2012, 03:55 pm
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, 2012void 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    }  }}`

#### foxyNik

#4
##### Aug 10, 2012, 04:07 pm
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);    }    Serial.println(""); }`

Go Up