Click here to Skip to main content
11,569,674 members (58,964 online)
Click here to Skip to main content

Convert a "Hex String" to an Integer

, 15 Jan 2001 391.6K 1.6K 21
Rate this:
Please Sign up or sign in to vote.
Convert a string containing a hex value to an integer
<!-- Link to demo file download -->
  • Download demo project - 8 Kb
  • <!-- Add the rest of your HTML here -->

    Convert a "Hex String" to an Integer

    Sometimes I have had a string containing a Hex Value like char s[10] = "0xFDE8"; that I would like to convert to an integer (in this case it would of course get the value 65000). I have not been able to find any standard C or C++ functions to do that, so I decided to write my own. It's declared as _httoi(const TCHAR *value) and is coded using TCHAR so it works both with and without UNICODE defined

    It's possible it could be done smarter and faster, but it works and if you like it it's yours to use for free.

    Here is the code to a small console application that uses the function, and demostrates its use.

    #include "stdafx.h"
    #include <tchar.h>
    #include <malloc.h>
    
    int _httoi(const TCHAR *value)
    {
      struct CHexMap
      {
        TCHAR chr;
        int value;
      };
      const int HexMapL = 16;
      CHexMap HexMap[HexMapL] =
      {
        {'0', 0}, {'1', 1},
        {'2', 2}, {'3', 3},
        {'4', 4}, {'5', 5},
        {'6', 6}, {'7', 7},
        {'8', 8}, {'9', 9},
        {'A', 10}, {'B', 11},
        {'C', 12}, {'D', 13},
        {'E', 14}, {'F', 15}
      };
      TCHAR *mstr = _tcsupr(_tcsdup(value));
      TCHAR *s = mstr;
      int result = 0;
      if (*s == '0' && *(s + 1) == 'X') s += 2;
      bool firsttime = true;
      while (*s != '\0')
      {
        bool found = false;
        for (int i = 0; i < HexMapL; i++)
        {
          if (*s == HexMap[i].chr)
          {
            if (!firsttime) result <<= 4;
            result |= HexMap[i].value;
            found = true;
            break;
          }
        }
        if (!found) break;
        s++;
        firsttime = false;
      }
      free(mstr);
      return result;
    }
    
    int main(int argc, char* argv[])
    {
      TCHAR *test[4] = {_T("0xFFFF"), _T("0xabcd"), _T("ffff"), _T("ABCD")};
      for (int i = 0; i < 4; i++)
        _tprintf(_T("Hex String: %s is int: %d\n\r"), test[i], _httoi(test[i]));
      return 0;
    }
    

    Well, that's all there is to it. You can either copy the code from your browser, or download the project for Visual C++ 6.0.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    Share

    About the Author

    Anders Molin
    Software Developer (Senior)
    Denmark Denmark
    Huh! Wink | ;-)

    You may also be interested in...

    Comments and Discussions

     
    QuestionLicense? Pin
    Member 896106510-Jul-12 2:50
    memberMember 896106510-Jul-12 2:50 
    GeneralInteger string (64bit) to hex having only 32 bit Pin
    RomanoScuri13-Sep-10 22:41
    memberRomanoScuri13-Sep-10 22:41 
    GeneralOh my god- so much code and for what??? Something that is already done with one line using "strtol" Pin
    TheBishop7-May-09 5:39
    memberTheBishop7-May-09 5:39 
    Generalefficient & no library dependencies: Pin
    tektor15-Dec-08 12:04
    membertektor15-Dec-08 12:04 
    Generaldead horse Pin
    c. leamon11-Sep-07 4:08
    memberc. leamon11-Sep-07 4:08 
    QuestionWhy re-invent the wheel ? Pin
    damnedyankee8-Dec-06 1:10
    memberdamnedyankee8-Dec-06 1:10 
    AnswerRe: Why re-invent the wheel ? Pin
    Francesco Pratolongo4-Apr-07 9:22
    memberFrancesco Pratolongo4-Apr-07 9:22 
    GeneralShorter Code Pin
    nfalabi29-Oct-06 19:08
    membernfalabi29-Oct-06 19:08 
    GeneralRe: Shorter Code Pin
    as_sound_as6-May-07 6:56
    memberas_sound_as6-May-07 6:56 
    'swscanf' was declared deprecated

    you can use also

    CString s = _T("1A");
    long k = wcstol( _T("0x") + s , 0, 0 );

    Smile | :)

    General:) nice but... Pin
    nicekr14-Aug-06 4:12
    membernicekr14-Aug-06 4:12 
    Generalgreat!! Pin
    KIM HyunJoong3-Jul-06 19:05
    memberKIM HyunJoong3-Jul-06 19:05 
    Generalsscanf will do too ... Pin
    Anonymous27-Sep-05 3:08
    sussAnonymous27-Sep-05 3:08 
    GeneralRe: sscanf will do too ... Pin
    spinoza4-Jan-06 15:53
    memberspinoza4-Jan-06 15:53 
    GeneralThanks Pin
    Codin' Carlos16-Oct-02 19:58
    memberCodin' Carlos16-Oct-02 19:58 
    GeneralRe: Thanks Pin
    Anonymous17-Nov-04 5:00
    sussAnonymous17-Nov-04 5:00 
    GeneralRe: Thanks Pin
    c4l23-Apr-06 11:26
    memberc4l23-Apr-06 11:26 
    General;P If you speaking about C++ then this is the solution for converting a hexadecimal string to an integer Pin
    Anonymous12-Jun-02 2:19
    memberAnonymous12-Jun-02 2:19 
    GeneralUse strtol. Pin
    Anonymous25-Jul-02 11:00
    sussAnonymous25-Jul-02 11:00 
    GeneralString to Int Pin
    Komtiki21-Apr-02 22:01
    memberKomtiki21-Apr-02 22:01 
    GeneralRe: String to Int Pin
    Anders Molin8-May-02 11:33
    memberAnders Molin8-May-02 11:33 
    GeneralTry This also Pin
    NMS10-Aug-01 0:45
    memberNMS10-Aug-01 0:45 
    GeneralUsing CString again... Pin
    Liqo14-Mar-01 5:03
    memberLiqo14-Mar-01 5:03 
    GeneralSlooooooow lookup Pin
    Oz Solomonovich17-Jan-01 6:33
    memberOz Solomonovich17-Jan-01 6:33 
    GeneralAnother way -- using CString Pin
    Paul Wolfensberger14-Jan-01 5:32
    memberPaul Wolfensberger14-Jan-01 5:32 
    Generalstd::stringstream Pin
    Wilka12-Jan-01 12:33
    memberWilka12-Jan-01 12:33 

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

    | Advertise | Privacy | Terms of Use | Mobile
    Web03 | 2.8.150624.2 | Last Updated 16 Jan 2001
    Article Copyright 2001 by Anders Molin
    Everything else Copyright © CodeProject, 1999-2015
    Layout: fixed | fluid