unsigend char negieren
-
Huhu,
kann mir jemand erklären, wieso bei ...#include <iostream> using namespace std; int main() { unsigned char c = 0; cout << ~c; // ... -1 rauskommt, und nicht 255? return 0; }Danke im Voraus.
-
ISO/IEC 5.3.1 (9) schrieb:
The operand of ~ shall have integral or enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand. (...)
Im Ausdruck ~c wird c zunächst werterhaltend in einen int umgewandelt, und dessen Bits werden dann umgekehrt. Das Ergebnis ist vom Typ int.
-
Das sind die arkanen Regeln der "integral promotion". Das c wird vor dem Berechnen von ~ in einen int umgewandelt, ~0 ist -1 und das Ergebnis ist dann auch vom Typ int und wird entsprechend ausgegeben.
edit: Zu langsam.
-
Ach, natürlich. Bin gerade selbst drauf gekommen. Bevor die Operation
~gemacht wird, wirducja zuintpromoted. Und int i = 0 negiert ist nunmal -1.edit: ;), Danke euch trotzdem.

-
Gugelmoser schrieb:
Und int i = 0 negiert ist nunmal -1.
0 negiert ist 0.
Und der Wert von ~0 muss auch nicht -1 sein (Zweierkomplement), er kann auch -0 (Einerkomplement) oder INT_MIN sein (Sign+Magnitude).
Das Ergebnis von Bitoperationen auf vorzeichenbehafteten Ganzzahlen ist implementierungsabhängig.
-
Und wenn das nicht so wäre, würde auch nicht 255 raus kommen, sondern das entsprechende Ascii-Zeichen.