Thread: Convert hex back to int?

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    36

    Exclamation Convert hex back to int?

    Hi. I have a file to read, in this format:
    Code:
    0,0,0,0,0,0,0,0,0,0,6,0x01
    1,0,0,0,0,0,0,0,0,0,0,0x02
    2,0,0,0,0,0,0,0,0,0,0,0x04
    My function is this:
    Code:
    void Tile::ReadTileData(char* line)
    {
    	char* buffer;
    
    	buffer = strtok (line, ",");
    	while (buffer != NULL)
    	{
    		tile_data.push_back(atoi(buffer));
    		buffer = strtok (NULL, ",");
    	}
    }
    Now this reads all values fine and stores them as ints, but the last hex value is always stored as 0. Is there any way to get it to parse the string in as an int?

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    You need to recognize the prefix 0x. Then you parse the remainder as a hex string. If you used C++, you can use stringstream's setbase to do that.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Or use "strtol" which automatically recognizes decimal, hex and octal numbers unless you specify a base.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Drawing Program
    By Max_Payne in forum C++ Programming
    Replies: 21
    Last Post: 12-21-2007, 05:34 PM
  2. Replies: 26
    Last Post: 11-30-2007, 03:51 AM
  3. Switch/case Problems (long code in post)
    By Wraithan in forum C++ Programming
    Replies: 2
    Last Post: 12-01-2005, 06:40 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 06:05 PM