Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

hex values c++ ...

  • 17-02-2011 10:55pm
    #1
    Closed Accounts Posts: 6,556 ✭✭✭


    Eh, this is mad .. but i am using hex numbers in a c++ program
    yet they are being treated like decimal numbers, so i did a simple test :
    int main()
    {
     
        int x = 0x9;
        int y = 0x7;
        int z = x+y;
        cout <<z;
    
        return 0;
    }
     
    

    I am getting 16 as the value of z, rather then 0x10 ,

    do i need more then the 0x to state that it is in hex ?


Comments

  • Registered Users, Registered Users 2 Posts: 2,426 ✭✭✭ressem


    it doesn't matter whether you enter
    int x = 0x0F;
    or
    int x = 15
    you are just setting x to 00000000...00001111 binary

    The base that you used originally isn't stored.
    What you are looking to do is set the output format to hex to display the binary number using a different base than the default which is decimal.

    this can be done by
    std::cout<<std::hex<<z

    or
    cout<<hex<<z
    when you are using namespace std

    http://www.cplusplus.com/reference/iostream/manipulators/hex/

    and if you want to display the 0x prefix then you use
    cout<<hex<<showbase<<z


Advertisement