Click here to Skip to main content
6,932,810 members and growing! (15,932 online)
Email Password   helpLost your password?
 
General Programming » String handling » Text Conversion     Intermediate

Convert a "Hex String" to an Integer

By Anders Molin

Convert a string containing a hex value to an integer
VC6Win2K, Dev
Posted:11 Jan 2001
Updated:15 Jan 2001
Views:302,181
Bookmarked:19 times
printPrint Friendly   add Share
      Discuss Discuss   Broken Article?Report  
30 votes for this article.
Popularity: 4.95 Rating: 3.35 out of 5
3 votes, 23.1%
1

2
1 vote, 7.7%
3
1 vote, 7.7%
4
8 votes, 61.5%
5
  • Download demo project - 8 Kb
  • 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

    About the Author

    Anders Molin


    Member
    Huh! Wink
    Occupation: Software Developer (Senior)
    Location: Denmark Denmark

    Other popular String handling articles:

    Article Top
    You must Sign In to use this message board.
    FAQ FAQ 
     
    Noise Tolerance  Layout  Per page   
     Msgs 1 to 25 of 31 (Total in Forum: 31) (Refresh)FirstPrevNext
    GeneralOh my god- so much code and for what??? Something that is already done with one line using "strtol" PinmemberTheBishop6:39 7 May '09  
    Generalefficient & no library dependencies: Pinmembertektor13:04 15 Dec '08  
    Generaldead horse Pinmemberc. leamon5:08 11 Sep '07  
    GeneralWhy re-invent the wheel ? Pinmemberdamnedyankee2:10 8 Dec '06  
    GeneralRe: Why re-invent the wheel ? PinmemberFrancesco Pratolongo10:22 4 Apr '07  
    GeneralShorter Code Pinmembernfalabi20:08 29 Oct '06  
    GeneralRe: Shorter Code Pinmemberas_sound_as7:56 6 May '07  
    General:) nice but... Pinmembernicekr5:12 14 Aug '06  
    Generalgreat!! PinmemberKIM HyunJoong20:05 3 Jul '06  
    Generalsscanf will do too ... PinsussAnonymous4:08 27 Sep '05  
    GeneralRe: sscanf will do too ... Pinmemberspinoza16:53 4 Jan '06  
    GeneralThanks PinmemberCodin' Carlos20:58 16 Oct '02  
    GeneralRe: Thanks PinsussAnonymous6:00 17 Nov '04  
    GeneralRe: Thanks Pinmemberc4l12:26 23 Apr '06  
    General;P If you speaking about C++ then this is the solution for converting a hexadecimal string to an integer PinmemberAnonymous3:19 12 Jun '02  
    GeneralUse strtol. PinsussAnonymous12:00 25 Jul '02  
    GeneralString to Int PinmemberKomtiki23:01 21 Apr '02  
    GeneralRe: String to Int PinmemberAnders Molin12:33 8 May '02  
    GeneralTry This also PinmemberNMS1:45 10 Aug '01  
    GeneralUsing CString again... PinmemberLiqo6:03 14 Mar '01  
    GeneralSlooooooow lookup PinmemberOz Solomonovich7:33 17 Jan '01  
    GeneralAnother way -- using CString PinmemberPaul Wolfensberger6:32 14 Jan '01  
    Generalstd::stringstream PinmemberWilka13:33 12 Jan '01  
    GeneralWhy don't you use strtol()? PinmemberNicolas P12:07 12 Jan '01  
    GeneralRe: Why don't you use strtol()? PinmemberWilliam E. Kempf12:35 12 Jan '01  

    General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

    PermaLink | Privacy | Terms of Use
    Last Updated: 15 Jan 2001
    Editor: James Spibey
    Copyright 2001 by Anders Molin
    Everything else Copyright © CodeProject, 1999-2010
    Web20 | Advertise on the Code Project