Thread: convert a decimal int to hex

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    112

    convert a decimal int to hex

    Does anyone know a function that will convert a decimal integer to a hexidecimal in the form of a string.

    so 1 would become "01" or 10 would become "0A"
    thanks

  2. #2
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    sprintf(str,"%x",num); //I believe that's right
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    112
    Thanks, could you also tell me how to convert back?

  4. #4
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    sscanf is the same kind of thing.

    but a lot of people would tell you not to use that
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  5. #5
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    Do you want to simply output the hex version to the screen? If so, you might be able to use:

    float foo=4.5;
    cout<<hex<<foo;


    Not really sure though b/c I have never needed to output decimals in hex.

  6. #6
    Registered User
    Join Date
    Mar 2002
    Posts
    112
    FillYourBrain, thanks for the help. Can you tell me how to convert this hex string back to an integer though? I looked up sprintf but i can't figure out how to convert back, and it seems to me that its not possible .

    Oh yah, and is there a windows function to do this?
    Last edited by pinkcheese; 08-11-2002 at 11:28 PM.

  7. #7
    Registered User
    Join Date
    Jun 2002
    Posts
    267
    #include <iostream>
    Code:
    #include <stdlib.h>
    
    int main()
    {
    	char in_buffer[50];
    	std::cout << "Enter a number: ";
    	std::cin >> in_buffer;
    	std::cout << std::endl;
    		
    	int some_int = atoi(in_buffer);
    	char some_string[50];
    	itoa(some_int, some_string, 16);	// converts some_int to null-terminated string with radix of 16 (hex)
    	std::cout << "Hex: 0x0" << some_string << std::endl;
    	itoa(some_int, some_string, 10);	// converts some_int to null-terminated string with radix of 10 (dec)
    	int back_to_int = atoi(some_string);
    	std::cout << "Dec: " << back_to_int;
    	return 0;
    }
    Do a google search to find a much more sophisticated Windows version, there are plenty! Some are quite complicated! (but allow for unicode and radix specification)

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Can you tell me how to convert this hex string back to an integer though?
    There's no need to convert it back if all you are doing is printing the values. The original integer should still be intact:
    Code:
    #include <cstdio>
    #include <iostream>
    
    int main()
    {
      int val = 0;
      char buffer[20];
      
      std::cout<<"Enter a number: ";
      while ( std::cin>>val ) {
        sprintf ( buffer, "%#x", val );
        
        std::cout<<"Your number was "<< val <<std::endl;
        std::cout<<"In hexadecimal "<< buffer <<std::endl;
      }
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    on the other hand if you have a string input representing a hexidecimal number and you wish to convert it to decimal, then some additional work is necessary.

    Code:
    cout << "enter a hexadecimal value using standard notation" << endl;
    
    char input[80];
    cin >> input;
    int decimal;
    
    cout << "hexadecimal input " << input << " in decimal form is " << decimal;
    One way to accomplish conversion is as follows. First reverse the char in input by using strrev(). Then the index of the element is the power of 16. So if input is:

    AB3

    then reverse to get

    3BA

    and the decimal value is:

    3*16^0 + B*16^1 + A*16^2 where A is decimal equivalent of 10 and B is decimal equivalent of 11, etc. In order to do this however you first need to convert each char in the string to an int and store it in an int array. Here's one way to do that part:

    Code:
    int array[80];
    char temp[3];
    void convertHexCharToDecimalChar(char * input, int * array)
    {
      int i;
      for(i = 0; i < strlen(input); i++)
      {
         if(isdigit(input[i])
         {
            temp[0] = input[i];
            temp[1] = '\0';
            array[i] = atoi(temp);
            temp[0] = '\0';
          }
          else if(input[i] == 'A')
          {
             temp[0] = '1';
             temp[1] = '0';
             temp[2] = '\0';
             array[i] = atoi(temp);
             temp[0] = '\0';
           }
            else if(input[i] = 'B')
            {
               temp[0] = '1';
               temp[1] = '1';
               temp[2] = '\0';
              // etc.
       }
    }
         
    int decimal = 0;
    for(i = 0; i < strlen(input); i++)
    {
      decimal += array[i]*pow(16, i);
    }

  10. #10
    Unregistered
    Guest
    i actually had to write a program that had to convert to hex and back.

    char sw(int num)
    {
    char h[16] = {'0','1','2','3','4','5','6','7','8','9','A','B',' C','D','E','F'};

    return h[num];
    }

    void hex_help(long int num)
    {
    long int i, j, exp = 0, temp = num;
    char hex[100];

    while( temp >= 16)
    {
    exp++;
    temp /= 16;
    }

    for ( i = 0; i <= exp; ++i)
    {
    temp = num;
    for ( j = i; j <= exp; ++j)
    {
    if ( j == exp )
    hex[i] = sw(temp % 16);
    else
    temp /= 16;
    }
    }
    hex[exp + 1] = '\0';

    cout << hex;
    }



    int pow(long int x, long int y)
    {
    long int i, pow = x;

    if ( y > 1)
    {
    for (i = 0; i < y-1; ++i)
    {
    x *= pow;
    }
    return x;
    }

    if ( y == 0)
    return 1;

    if (y == 1)
    return x;

    }


    void hex()
    {
    char h[20], a;
    long int i, num = 0, len, j;
    system("cls");

    cout << "Enter hex (i.e. F8): ";
    cin >> h;

    len = strlen(h);

    for (i = 0; i < len; ++i)
    {
    h[i] = (char) toupper(h[i]);
    }

    for (i = 0, j = len-1; i < len ; ++i, --j)
    {
    switch (h[i])
    {
    case '0': num += 0; break;
    case '1': num += pow(16, j) * 1; break;
    case '2': num += pow(16, j) * 2; break;
    case '3': num += pow(16, j) * 3; break;
    case '4': num += pow(16, j) * 4; break;
    case '5': num += pow(16, j) * 5; break;
    case '6': num += pow(16, j) * 6; break;
    case '7': num += pow(16, j) * 7; break;
    case '8': num += pow(16, j) * 8; break;
    case '9': num += pow(16, j) * 9; break;
    case 'A': num += pow(16, j) * 10; break;
    case 'B': num += pow(16, j) * 11; break;
    case 'C': num += pow(16, j) * 12; break;
    case 'D': num += pow(16, j) * 13; break;
    case 'E': num += pow(16, j) * 14; break;
    case 'F': num += pow(16, j) * 15; break;
    }
    }


    cout << "\n\n\n\tNumber is: " << num;
    if (num < 256)
    {
    a = (char) num;
    cout << "\n\n\tANSCII is: " << a;
    }
    cout << "\n\n\nPress 1 to do hex again, any other to return to menu\n>>>";
    cin >> a;

    if (a == '1')
    hex();


    }

  11. #11
    Registered User
    Join Date
    Jun 2002
    Posts
    267
    yea but he wanted it converted to a string... ie: int 10 would become the string "0a"

  12. #12
    Unregistered
    Guest
    to change to a string just call: hex_help(num)

  13. #13
    Registered User
    Join Date
    Jun 2002
    Posts
    267
    oops... maybe I should have looked at the code first!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  3. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  4. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 06:05 PM
  5. A Simple (?) Problem
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 10-12-2001, 04:28 AM