Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to Convert String to Binary?

I want to convert a string, using the string class - to Binary. What is the fast way to do this character by character. Loop? Or is there some function out there that will convert for me? 1's and 0's binary.

A string being:

#include <string>
using namespace std;
int main(){
  myString = "Hello World";
}
like image 922
Derp Avatar asked Apr 17 '12 02:04

Derp


People also ask

How do you convert a string to binary?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

What is the easiest way to convert numbers to binary?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.

How do you convert data to binary in Python?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

Which typecast method is required to store string in a binary file?

WriteFile function (MSDN)


1 Answers

Using std::bitset would work:

#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
  string myString = "Hello World";
  for (std::size_t i = 0; i < myString.size(); ++i)
  {
      cout << bitset<8>(myString.c_str()[i]) << endl;
  }
}

Output:

01001000
01100101
01101100
01101100
01101111
00100000
01010111
01101111
01110010
01101100
01100100
like image 88
Jesse Good Avatar answered Oct 15 '22 09:10

Jesse Good