Skip to content

Instantly share code, notes, and snippets.

@soachishti
Last active October 10, 2015 10:04
Show Gist options
  • Save soachishti/7f51e64a3b8eb0054624 to your computer and use it in GitHub Desktop.
Save soachishti/7f51e64a3b8eb0054624 to your computer and use it in GitHub Desktop.
Convert String to binary and vice verse
#include <iostream>
#include <bitset>
using namespace std;
string stringToBinary(string str) {
string binary;
for (size_t i = 0; i < str.size(); i++)
{
binary += bitset<8>(str.c_str()[i]).to_string();
}
return binary;
}
unsigned long long saveToLong(string binary){
const short int sizeLimit = sizeof(unsigned long long) * 8;
const int noOfBits = binary.size() - 1;
if (noOfBits > sizeLimit){
int bitToRemove = noOfBits - sizeLimit;
binary.erase(binary.end() - bitToRemove, binary.end());
cout << endl << "****Loss of data string size greater than long (64 bit)****" << endl;
}
else {
//Add extra zeros
string tmp;
for (int i = 0; i < (sizeLimit - noOfBits) ; i++){
tmp += "0";
}
binary += tmp;
}
return bitset<sizeLimit>(binary).to_ullong();
}
string binaryToString (string binary) {
string str;
char tmp[8];
for (size_t i = 0; i < binary.size() ; i+=8) {
for (int j = 0; j < 8 ; j++) {
tmp[j] = binary[i+j];
}
str += (char)bitset<8>(tmp).to_ulong();
}
return str;
}
string longToString(long long int longData){
const short int sizeLimit = sizeof(unsigned long long int) * 8;
string binary = bitset<sizeLimit>(longData).to_string();
return binaryToString(binary);
}
int main(){
string str = "Syed Owais Ali Chishti";
cout << "String: " << str << endl << endl;
string binary = stringToBinary(str);
cout << "String to Binary: " << binary << endl << endl;
string binToStr = binaryToString(binary);
cout << "Binary to String: " << binToStr << endl << endl;
unsigned long long longData = saveToLong(binary);
cout << "Long Value (64 bits): " << longData << endl;
cout << "Long to String: " << longToString(longData) << endl << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment