How to convert a string into binary sequence in C++

2 Answers

0 votes
#include <iostream>
#include <bitset>

int main() {
    std::string s = "c++ pro";

    for (int i = 0; i < s.length(); i++) {
        std::bitset<8> bs4(s[i]);
        std::cout << bs4 << " ";
    }

    return 0;
}




/*
run:

01100011 00101011 00101011 00100000 01110000 01110010 01101111 

*/

 



answered May 8, 2021 by avibootz
0 votes
#include <iostream>

std::string toBinary(int n) {
    std::string binary;
    while (n != 0) {
        binary += (n % 2 == 0 ? "0" : "1");
        n /= 2;
    }
    return binary;
}

int main() {
    std::string s = "c++ pro";

    for (int i = 0; i < s.length(); i++) {
        std::cout << toBinary(s[i]) << " ";
    }

    return 0;
}




/*
run:

1100011 110101 110101 000001 0000111 0100111 1111011 

*/

 



answered May 8, 2021 by avibootz

Related questions

...