2017-08-14 66 views
-2

我有兩個值,0和30,我需要將它的二進制表示存儲在每個字節上。像:如何將int轉換爲二進制並連接爲C++中的字符

字節0 = 00000000

字節1 = 00011110

,然後將它們連接起來的一個字符串,將打印ASCII爲0(NULL)和30(記錄分隔符)。所以,不要打印「030」,但是我不能在這裏真正正確地打印,而且這些命令也不能正確打印。我知道這些不是很好的印刷品。

我在做這樣的:如果

string final_message = static_cast<unsigned char>(bitset<8>(0).to_ulong()); 
final_message += static_cast<unsigned char>((bitset<8>(answer.size())).to_ulong()); // where answer.size() = 30 
cout << final_message << endl; 

不知道它是正確的,我從來沒有因爲位集現在的工作。我認爲這是對的,但收到我的消息的服務器不斷告訴我這些數字是錯誤的。我很確定我需要的數字是0和30,因此,作爲唯一的部分,我不確定它的工作原理是那三條線,我在這裏提出這個問題。

這三條線是對的?有更好的方法來做到這一點?

+0

你需要了解你想要什麼非常清楚 – pm100

回答

1

一個字節(或一個char)包含一個8位值,無論是以二進制格式,十進制格式還是作爲打印在字符上的字符「查看」它的值都是相同的安慰。這只是你看待它的方式。

請看下面的例子。前兩個例子byte1byte2是你的問題中提到的那些例子。不幸的是,你不會在控制檯上看到太多內容。 因此我添加了另一個例子,它說明了以不同方式查看相同值65的三種方法。希望能幫助到你。

int main(){ 

    char byte1 = 0b00000000; 
    char byte2 = 0b00011110; 

    std::cout << "byte1 as 'int value': " << (int)byte1 << "; and as character: " << byte1 << endl; 
    std::cout << "byte2 as 'int value': " << (int)byte2 << "; and as character: " << byte2 << endl; 

    char a1 = 65; 
    char a2 = 'A'; 
    char a3 = 0b001000001; 

    std::cout << "a1 as 'int value': " << (int)a1 << "; and as character: " << a1 << endl; 
    std::cout << "a2 as 'int value': " << (int)a2 << "; and as character: " << a2 << endl; 
    std::cout << "a3 as 'int value': " << (int)a3 << "; and as character: " << a3 << endl; 

    return 0; 
} 

輸出:

byte1 as 'int value': 0; and as character: 
byte2 as 'int value': 30; and as character: 
a1 as 'int value': 65; and as character: A 
a2 as 'int value': 65; and as character: A 
a3 as 'int value': 65; and as character: A 
0

string final_message = static_cast<unsigned char>(bitset<8>(0).to_ulong()); 

不編譯。顯然,這裏不需要bitset,因爲您基本上是在路徑中添加額外的轉換。

如果我將上面的行分割爲2並使用+=,則結果字符串的大小爲2,幷包含值爲0和30的字符(我已使用調試器進行了檢查)。

所以我不知道你有什麼問題,因爲它似乎你想要做什麼......

相關問題