2013-09-21 178 views
1

我需要將字符串轉換爲具有第一個字符串的二進制代碼的字符串。 對於第一部分,我用這個:Fastest way to Convert String to Binary?工作完美,但我想不出一種方法將它寫入一個新的字符串。C++字符串轉換爲二進制代碼/二進制代碼轉換爲字符串

下面是我使用至今代碼:

for (size_t i = 0; i < outputInformations.size(); ++i) 
{ 
    cout << bitset<8>(outputInformations.c_str()[i]); 
} 

輸出:

01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100 

有沒有寫入到一個新的字符串這種方式?所以我有一個名爲「binary_outputInformations」的二進制代碼在裏面。

+1

['std :: ostringstream'](http://en.cppreference.com/w/cpp/io/basic_ostringstream)會讓你在那裏。 – WhozCraig

回答

2

您是否正在尋找?

string myString = "Hello World"; 
    std::string binary_outputInformations; 
    for (std::size_t i = 0; i < myString.size(); ++i) 
    { 
    bitset<8> b(myString.c_str()[i]); 
     binary_outputInformations+= b.to_string(); 
    } 

    std::cout<<binary_outputInformations; 

輸出:

0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

+0

完美工作 –

1

使用std::ostringstream(希望C ​​++ 11):

#include <iostream> 
#include <sstream> 
#include <bitset> 

std::string to_binary(const std::string& input) 
{ 
    std::ostringstream oss; 
    for(auto c : input) { 
     oss << std::bitset<8>(c); 
    } 
    return oss.str(); 
} 

int main() 
{ 
    std::string outputInformations("testusername\ntestpassword"); 
    std::string binary_outputInformations(to_binary(outputInformations)); 
    std::cout << binary_outputInformations << std::endl; 
} 

輸出:

01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100 
相關問題