Results 1 to 2 of 2

Thread: hex in C++

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 1999
    Posts
    1,800
    I know there is a hex command in the windows.h file but is there a way to convert to binary and decimal?

  2. #2
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    Well you don't really convert a number between radixes (not sure if that's the correct plural), you just convert the number to a string in different ways; all numbers are stored as binary after all.

    To output a number to a radix R (a radix is a base number - hex is radix 16, decimal is radix 10, binary is radix 2, etc) you can use the itoa() function like this:

    Code:
    char buf[50];       // just a buffer for working in
    int TheNumber = 64;
    printf("TheNumber in decimal is: %s", itoa(TheNumber, buf, 10));
    printf("TheNumber in hex is: %s", itoa(TheNumber, buf, 16));
    printf("TheNumber in binary is: %s", itoa(TheNumber, buf, 2));
    printf("TheNumber in octal is: %s", itoa(TheNumber, buf, 8));
    Alternatively, if you're using C++ and cin / cout, you can #include <iomanip> and use the stream manipulators like 'hex' and 'dec':

    Code:
    cout << hex << TheNumber     // prints TheNumber to radix 16
    Harry.

    "From one thing, know ten thousand things."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width