Pages: [1]   Go Down
Author Topic: Converting String to binary code  (Read 1366 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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!
Logged

Germany
Offline Offline
Faraday Member
**
Karma: 56
Posts: 2981
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

a clue only:

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

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 289
Posts: 25705
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

bitRead
Logged

"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.

Southern California
Offline Offline
Full Member
***
Karma: 0
Posts: 108
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
// 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
    }
  }
}
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you all for the reply!   smiley

This is my solution:

Code:
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("");
 }
Logged

Pages: [1]   Go Up
Jump to: