Search code examples
iosobjective-cnsstringios-bluetooth

I am converting NSString a=@"0x401A" into int16_t?


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.


Solution

  • 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