Thread: cout << oct << -12 << endl; ?

  1. #1
    Banned
    Join Date
    Nov 2007
    Posts
    678

    cout << oct << -12 << endl; ?

    Code:
    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
        int num;
        while (true)
        {
            cout << "N: ";
            cin >> num;
            if (! num) break;
            cout << hex << num << " " << dec << num << " " << oct << num << endl;
        }
        
        return 0;
    }
    output:
    N: 12
    c 12 14
    N: -12
    fffffff4 -12 37777777764
    N:0

    Question: Why negative numbers get strange values in hex and oct?
    Actually I feel the hex value is natural, since that's how a negative number is internally. But why oct output is garbage?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Because hex and octal are defaulting to unsigned int instead of signed, it would appear.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is this me or Windows?
    By carrotcake1029 in forum C Programming
    Replies: 9
    Last Post: 05-07-2008, 09:18 AM
  2. how to do printf( "%c", 12 ); via ostream cout ??
    By L.O.K. in forum C++ Programming
    Replies: 9
    Last Post: 01-08-2005, 06:37 PM
  3. simple question (cout << "two words")
    By bleach in forum C++ Programming
    Replies: 3
    Last Post: 12-29-2001, 12:49 PM
  4. cout << double
    By Seron in forum C++ Programming
    Replies: 2
    Last Post: 12-28-2001, 10:14 AM
  5. Can't figure out why?
    By kwigibo in forum C Programming
    Replies: 10
    Last Post: 10-14-2001, 10:58 PM