String with hex value to int value

Discussion in 'Mac Programming' started by hiddenpremise, Jul 26, 2010.

  1. hiddenpremise macrumors regular

    hiddenpremise

    Joined:
    Jul 25, 2008
    Location:
    Somewhere between my imagination and reality
    #1
    I am giving myself a headache over a seemingly simple problem
    I have an NSString containing hex values "0x74 0x68 0x69 0x73 0x20 0x69 0x73 0x20 0x61 0x20 0x73 0x74 0x72 0x69 0x6e 0x67"

    I convert that to array NSArray * myArray = [myString componentsSeparatedByString:mad:" "];

    I then want to convert each of those strings to an int value.

    How do I get from "0x73" to 115 to "s"?

    I have tried calling [[myArray objectAtIndex:i] integerValue]; but that doesn't seem to work

    Solved. Thanks for your help everyone!
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    I don't have time to write the code, but %x is the format specifier for hex. With C functions you could do the conversion, I'm not sure if there are similar things available for NSNumber, NSString, etc.

    -Lee
     
  3. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #3
    Break the problem down.

    You've already broken it down once, by splitting the string into multiple strings. Break it down again until you have something you know how to solve.

    Look at the NSScanner class reference docs, and see if it has anything for hex numbers.

    integerValue can't possibly work, because it only decodes decimal representations (i.e. base 10), and hexadecimal is base 16. Read the reference doc for that NSString method.

    Also, "0x" is only a marker, and not actually part of the numeric value. So one part of breaking it down is going to be skipping the "0x" part.
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    As Objective-C is a superset of C you could just use the C functions.
     
  5. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #5
    Looking at scanHexInt:, you shouldn't need to go to this trouble.

    -Lee
     
  6. jared_kipe macrumors 68030

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #6
    You don't need to create a NSScanner object to acomplish this.

    Code:
    
    int n;
    	NSString *s = @"0x544";
    	sscanf([s UTF8String], "%x", &n);
    
    
    n will be a regular int that you can put into an NSNumber if need be.

    Even better.

    Code:
    #import <Cocoa/Cocoa.h>
    
    @interface NSString (HexValue) 
    -(int) hexValue;
    @end
    
    
    @implementation NSString (HexValue)
    - (int) hexValue {
    	int n = 0;
    	sscanf([self UTF8String], "%x", &n);
    	return n;
    }
    @end
    
    then just call [(NSString) *)s hexValue] and it will return the int!
     

Share This Page