Thread: Signed hex conversion

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    21

    Signed hex conversion

    I need to be able to convert hex values to a signed integer. I'm currently using the below:

    strtol(data, NULL, 16);

    but when data is equal to something like 'FFFFFE' the result comes out to be massively positive instead of small and negative. Can anyone tell me how I can retrieve the negative result?

    Thanks,
    James

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This sounds like Convert string to signed hex.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    What I did is set a variable to a hex value, then use the variable as an integer. Like so.

    Code:
    #include <stdio.h>
    
    int main()
    {
    	int hex;
    	printf("Hex: ");
    	scanf("%x", &hex);
            printf("Decimal: %d\n", hex);
    	return 0;
    }
    I input "FF" and it returned "255" (which is correct). Is this what you're trying to do?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 18
    Last Post: 03-26-2008, 09:01 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 11
    Last Post: 03-24-2006, 11:26 AM
  4. Hex to binary conversion and storing in nybble
    By shoobsie in forum C Programming
    Replies: 14
    Last Post: 10-25-2005, 02:51 AM
  5. Header File Question(s)
    By AQWst in forum C++ Programming
    Replies: 10
    Last Post: 12-23-2004, 11:31 PM