-1

My question will be Arduino specific, I wrote a code that turns array of characters (text) into binary string, but the problem is that the binary representation is not 8 bits, its sometimes 7 bits, 6 bits or even 1 bit representation (if you have a value of 1 as decimal). I'm using String constructor String(letter, BIN) to store the binary representation of letter in a string.

I would like to have a 8 bits representation or even a 7 bits representation.

String text = "meet me in university";
String inbits;
byte after;
byte bits[8];
byte x;
char changed_char;
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Press anything to begin");
  inbits = convertToBits(text);
}

String convertToBits(String plaintext)
{
  String total,temp;
  total = String(plaintext[0],BIN);
  total = String(total + " ");
  for (int i=1;i<plaintext.length();i++)
  {
    temp = String (plaintext[i],BIN);
    total = String(total + temp);
    total = String(total + " ");
  }
  Serial.println(total);
  return total;
}
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Abdullah
  • 11
  • 1

3 Answers3

1

If the length of the argument string is less then 8, prepend "0"s until it is 8 bits long.

EvilTeach
  • 28,120
  • 21
  • 85
  • 141
1

You could do something similar to the following:

void PrintBinary(const std::string& test)
{
    for (int c = 0; c < test.length(); c++)
    {
        unsigned bits = (unsigned)test[c];
        for (int i = 0; i < 8; i++)
        {
            std::cout << ((bits >> (7 - i)) & 1U);
        }
        std::cout << " ";
    }
}

Modifying the above example to use String and Serial.println instead of std::string and std::cout should be trivial. I don't own an arduino to test with so I couldn't modify your code and test if the above is possible in the environment you work in but I assume it is.

PrintBinary("Hello"); //Output: 01001000 01100101 01101100 01101100 01101111   
Jim Nilsson
  • 838
  • 4
  • 12
0

String(letter, BIN) doesn't zero pad the string. You have to do it yourself.

You need to prepend the 0 character until your binary string is 8 characters long.

String convertToBits(String plaintext)
{
  String total, temp;
  total = "";
  for (int i=0; i<plaintext.length(); i++)
  {
    temp = String (plaintext[i], BIN);
    while (temp.length() < 8)
        temp = '0' + temp;
    if (i > 0)
        total = String(total + " ");
    total = String(total + temp);
  }
  Serial.println(total);
  return total;
}
gre_gor
  • 6,669
  • 9
  • 47
  • 52