2013-02-01 68 views
32
#include <iostream> 

using namespace std; 

int main() 
{ 
    char   c1 = 0xab; 
    signed char c2 = 0xcd; 
    unsigned char c3 = 0xef; 

    cout << hex; 
    cout << c1 << endl; 
    cout << c2 << endl; 
    cout << c3 << endl; 
} 

我預期的產量如下:如何通過cout將整個字符輸出爲整數?

ab 
cd 
ef 

然而,我什麼也沒得到。

我想這是因爲cout始終將'char','signed char'和'unsigned char'視爲字符而不是8位整數。但是,'char','signed char'和'unsigned char'都是整型。

所以我的問題是:如何通過cout輸出一個字符爲整數?

PS:static_cast(...)是醜陋的,需要更多的工作來修剪額外的位。

+0

據我所知,鑄造是最有效的方法...(例如'的static_cast ()') – Nim

+0

它鑄造成'int'? –

+1

btw。你需要採取「修整」的唯一原因是你顯然沒有正確使用類型(前兩個*清楚*溢出),這就是你得到的結果。如果你總是使用正確的類型,那麼演員陣容就是:'static_cast (...)'...... – Nim

回答

65
char a = 0xab; 
cout << +a; // promotes a to a type printable as a number, regardless of type. 

只要類型提供一個具有普通語義的一元運算符+,它就可以工作。如果您要定義一個代表數字的類,要爲規則語義提供一元+運算符,請創建一個operator+(),該值只需按值或引用常量返回*this即可。

來源:Parashift.com - How can I print a char as a number? How can I print a char* so the output shows the pointer's numeric value?

+1

工作鏈接:http://www.cs.technion.ac.il/users/yechiel /c++-faq/print-char-or-ptr-as-number.html – GetFree

+1

這是相當模糊的。 [sheu的回答](https://stackoverflow.com/a/14644745/1557062)中的一個簡單的'static_cast'明確表達了這個意圖。 – sigy

7

它們轉換成整數類型,(並適當位掩碼!)即:

#include <iostream> 

using namespace std; 

int main() 
{ 
    char   c1 = 0xab; 
    signed char c2 = 0xcd; 
    unsigned char c3 = 0xef; 

    cout << hex; 
    cout << (static_cast<int>(c1) & 0xFF) << endl; 
    cout << (static_cast<int>(c2) & 0xFF) << endl; 
    cout << (static_cast<unsigned int>(c3) & 0xFF) << endl; 
} 
+2

'c1'和'c2'的輸出是'ffffffab'和'ffffffcd',這不是OP預期的結果。 –

+0

@ Mr.C64好點。編輯,謝謝。 – sheu

+0

但是,'char','signed char'和'unsigned char'都是整型。 static_cast(...)是醜陋的,需要更多的工作來修剪額外的位。 – xmllmx

3

也許這:

希望它能幫助。

相關問題