CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Hex2Dec!!!

  1. #1
    Join Date
    Apr 1999
    Posts
    31

    Hex2Dec!!!

    Hi All,
    Is there any built-in function to convert an Hexadecimal value to Decimal value(Integer,not float)and viceversa. OR is there any easy way of doing it.---- But I want it to work for a wide range of values.

    The Exact problem is --- I have an application where the user is asked to type a value and this value is the input to my function. Here I am using an Edit Box to get the input--- and the input to my function must be a hexa value.

    --To be precise, If the user types in 20000 in the edit box, and I use GetDlgItemText()function to get the string value and use atol()function to get the integer value. I value I get will be 20000 only and not 20000hexa or not even the decimal value of 20000.

    Thanks in Advance...
    Vittal


  2. #2
    Join Date
    Jun 1999
    Posts
    23

    Re: Hex2Dec!!!

    To Vittal

    Here is some code that might help.

    unsigned long CSomeClass::ToDecimal( CString HexNumber )
    {
    unsigned long Answer = 0, PrevUnit = 1;

    HexNumber.MakeReverse();

    for( int i=0; i<HexNumber.GetLength(); i++ )
    {
    switch( HexNumber.GetAt[i] )
    {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9: Answer += (HexNumber.GetAt[i] - '0' * PrevUnit); break;
    case 'a':
    case 'b':
    case 'c':
    case 'd':
    case 'e':
    case 'f': Answer += ((HexNumber.GetAt[i] - ('a'-10)) * PrevUnit); break;
    }
    PrevUnit *= 16;
    }

    return Answer;
    }

    Matthew Cross


  3. #3
    Join Date
    May 1999
    Location
    Seattle, WA USA
    Posts
    423

    Re: Hex2Dec!!!

    use strtol.bool HexToDecimal (char* HexNumber, int& Number)
    {
    char* pStopString;
    Number = strtol (HexNumber, &pStopString, 16);
    return (bool)(Number != LONG_MAX);
    }

    HTH
    --michael


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

Featured