Operationen auf negative Zahlen in GCC



  • Hi,

    Einige Fragen zur Operationen auf negative Zahlen in GCC.

    int a;	// angenommen, dass das höchste Bit von 'a' EINS ist, also negative.
    unsigned int b;
    

    1. Bekommt man immer 'wahr' bei 'if (b >= a)'?

    2. b = a;
    Was ist 'b' jetzt?

    3. a >> 1; oder a << 1;
    Verliert 'a' das Vorzeichen?

    Gruss
    Senmeis


  • Mod

    senmeis schrieb:

    1. Bekommt man immer 'wahr' bei 'if (b >= a)'?

    nein.

    2. b = a;
    Was ist 'b' jetzt?

    UINT_MAX + 1 + a (als mathematischer Term)

    3. a >> 1; oder a << 1;
    Verliert 'a' das Vorzeichen?

    Bei a >> 1 hängt das Ergebnis von der Implementation ab
    Bei a << 1 kommt es auf das höchstwertige Bit von a an

    Wie das Ganze konkret bei gcc aussieht, wird im Manual beschrieben



  • camper schrieb:

    Bei a << 1 kommt es auf das höchstwertige Bit von a an

    und das bit rechts daneben.
    🙂


  • Mod

    -fricky- schrieb:

    camper schrieb:

    Bei a << 1 kommt es auf das höchstwertige Bit von a an

    und das bit rechts daneben.
    🙂

    Der Smiley ist überflüssig. Im Übrigen bist du nicht qualifiziert genug, Sätze für mich zu korrigieren.

    Immerhin ist die Aussage tatsächlich zu korrigieren: das Verhalten ist undefiniert.



  • camper schrieb:

    Im Übrigen bist du nicht qualifiziert genug, Sätze für mich zu korrigieren.

    das war keine korrektur sondern eine ergänzung. also nicht gleich beleidigt sein.
    🙂



  • [quote="camper"]

    senmeis schrieb:

    1. Bekommt man immer 'wahr' bei 'if (b >= a)'?

    nein.

    vielen Dank.
    'b' ist positive und 'a' ist negative. Warum ist das Ergebnis nicht wahr?

    Gruss
    Senmeis


  • Mod

    Beachte die Antwort zur zweiten Frage. Bei den meisten binären Operatoren müssen beide Operanden zunächst in einen gemeinsamen Typ (hier: unsigned) konvertiert werden.



  • Vielleicht hilft auch das hier:

    ISO/IEC 14882 (2003) schrieb:

    • If either operand is of type long double, the other shall be converted to long double.

    • Otherwise, if either operand is double, the other shall be converted to double.

    • Otherwise, if either operand is float, the other shall be converted to float.

    • Otherwise, the integral promotions (4.5) shall be performed on both operands.

    • Then, if either operand is unsigned long the other shall be converted to unsigned long.

    • Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int;
      otherwise both operands shall be converted to unsigned long int.

    • Otherwise, if either operand is long, the other shall be converted to long.

    • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.


Anmelden zum Antworten