2013-02-01 14 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; 
} 

mi aspettavo l'uscita sono i seguenti:Come emettere un carattere come numero intero tramite cout?

ab 
cd 
ef 

Eppure, non ho niente.

Immagino che questo sia dovuto al fatto che cout considera sempre "char", "signed char" e "unsigned char" come caratteri anziché interi a 8 bit. Tuttavia, "char", "signed char" e "unsigned char" sono tutti tipi interi.

Quindi la mia domanda è: come generare un carattere come un intero attraverso cout?

PS: static_cast (...) è brutto e ha bisogno di più lavoro per tagliare i bit in più.

+0

afaik, casting è il modo più efficace ... (ad esempio 'static_cast ()') – Nim

+0

colata a 'int'? –

+1

btw. l'unica ragione per cui hai bisogno di ricorrere al "trimming" è che chiaramente non stai usando i tipi correttamente (i primi due * chiaramente * overflow) e questo è ciò che ottieni come risultato. Se hai sempre usato il tipo corretto, il cast è semplicemente, 'static_cast (...)' ... – Nim

risposta

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

Questo funziona fino a quando il tipo fornisce un unario + operatore con la semantica ordinarie. Se si sta definendo una classe che rappresenta un numero, per fornire un operatore unario + con semantica canonica, creare uno operator+() che restituisce semplicemente *this in base al valore o tramite riferimento-a-const.

fonte: 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

Link di lavoro: http://www.cs.technion.ac.il/users/yechiel /c++-faq/print-char-or-ptr-as-number.html – GetFree

+1

Questo è piuttosto offuscato. Un semplice 'static_cast' come in [sheu's answer] (https://stackoverflow.com/a/14644745/1557062) trasmette chiaramente l'intenzione. – sigy

7

le precipitava un tipo integer, (e maschera di bit in modo appropriato!) Cioè .:

#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

E l'output di 'c1' e' c2' è 'ffffffab' e' ffffffcd', che è _non_ cosa l'OP si aspetta. –

+0

@ Mr.C64 Buon punto. Modificato, grazie. – sheu

+0

Tuttavia, "char", "signed char" e "unsigned char" sono tutti tipi interi. static_cast (...) è brutto e ha bisogno di più lavoro per tagliare i bit extra. – xmllmx

3

Forse questo:

Speranza che aiuta.

Problemi correlati