0

Why when I am trying to convert it converts hexadecimal value into integer?

unsigned int outVal;
NSScanner* scanner = [NSScanner scannerWithString:final1];
[scanner scanHexInt:&outVal];
NSLog(@"%u",outVal);

Another way I am trying to do is converting it to normal integer it gives me 0 value. I just want the same characters:

int16_t a=0x401A;

I am getting this number from user so dont have the control to define it myself. I want removed quotations and datatype int16_t so I can execute command.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ab jatoi
  • 39
  • 6
  • If you use a hex format (@"%X") in `NSLog` do you see the right value? – Phillip Mills Nov 15 '16 at 15:44
  • yes i see the right value, but i need this in integer to pass the command to BLE device – ab jatoi Nov 15 '16 at 16:59
  • You're missing the point. The integer has the right numeric value; whether you see it as hex or decimal is only a function of the format string you use in `NSLog()`. – Phillip Mills Nov 15 '16 at 17:15
  • but BLE device only accepts command in 0x401A in this format. If i convert this hex into integer then i miss this '0x' then bluetooth device thinks wrong command. – ab jatoi Nov 15 '16 at 17:24
  • 1
    The '0x' is part of a string. It's not part of an integer value. If the device needs to see '0x' in the command, then it's expecting you to send a string. – Phillip Mills Nov 15 '16 at 17:34
  • but normally i am sending the command like int16_t=0x401A works perfectly for me. It doesn't expect the string to be honest. – ab jatoi Nov 15 '16 at 18:08
  • One more try...run this and see if it gives you any ideas: `int16_t a=0x401A; NSLog(@"0x401A = %u", a); int16_t b=16410; NSLog(@"16410 = 0x%X", b);` – Phillip Mills Nov 15 '16 at 18:39

1 Answers1

0

I got the solution myself

first the function which converts the data into bytes

    - (NSData *)dataWithString:(NSString *)hexstring
{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= hexstring.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [hexstring substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}

and call the function by giving parameters in the command which will be sent to BLE

NSData * data = [self  dataWithString: @"401A"];
[peripheral writeValue:data forCharacteristic:characteristic                                       
                            type:CBCharacteristicWriteWithResponse];

Through this code anybody can sent string to BLE device. Thanks and Cheers

ab jatoi
  • 39
  • 6