0

First i have to convert Hex but this <> generates an exception when i am trying to convert it to integer

NSString *steps =characteristic.value;
int value2= [steps intValue];

First i have to removce <>, then convert this hexadecimal string into integer value.

  • print out `characteristic` with NSLog to see what you have. What type of object was assigned to value and what is characteristic? – Volodymyr B. Nov 10 '16 at 09:55
  • `characteristic.value` is a `NSData` object. So use `NSData` and `getBytes:length:` Do not use `description`, that's bad habits. – Larme Nov 10 '16 at 09:56
  • 2
    Possible duplicate of [Transform NSData to int in Objective-c](http://stackoverflow.com/questions/25508138/transform-nsdata-to-int-in-objective-c) – Larme Nov 10 '16 at 09:56
  • Use `scanHexInt:` from `NSScanner` – clemens Nov 10 '16 at 09:59
  • i am getting hexadecimal value <000000ae> which is right, i just want to convert that value from hexadecimal string into integer value –  Nov 10 '16 at 10:00
  • You should read the `<` with `scanString:intoString:`, and than call `scanHexnt:`. – clemens Nov 10 '16 at 10:02
  • "i just want to convert that value from hexadecimal string", it should be a hex NSData, not a hex string. As I said, don't use description. `NSString *steps =characteristic.value;` should throw a warning (putting a `NSData` object into `NSString` object.) – Larme Nov 14 '16 at 15:20

2 Answers2

0

NSString *strVal = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding]; int intValue = strVal.intValue;

-1

You have to prefix your string with 0x:

NSString *orig = @"000000ae";
NSString *str = [NSString stringWithFormat:@"0x%@" , orig];

to be able to use NSScanner:

unsigned int outVal;
NSScanner* scanner = [NSScanner scannerWithString:str];
[scanner scanHexInt:&outVal];

outVal holds your result now.

shallowThought
  • 19,212
  • 9
  • 65
  • 112