蓝牙开发中数据处理的那些事

2020-11-11  本文已影响0人  Gordon_gc

蓝牙开发就会涉及到相关数据的处理,如下整理的是开发中用的到的知识点(后续会不断更新)

NSData与Byte的转换

int allDataLength = (int)allData.length;
Byte allDataByte[allDataLength];
[allData getBytes:&allDataByte length:allDataLength];

两位NSData转int

int value=*(int*)([intdata bytes]);

两位NSData高低字节转换成int

int heartCount = 0;
//获取心率数据
Byte heart[2];
heart[0] = allDataByte[10];
heart[1] = allDataByte[11];
NSData *heartData = [NSData dataWithBytes:heart length:2];
//这样获取到的值是高低字节转化过的
//例如:0xff00,转换的数据是0x00ff的值,也就是255
[heartData getBytes:&heartCount length:2];

数值转16进制字符串

//转换出来的字符串是小写字母,如需大写再进行转换
- (NSString*)stringWithHexNumber:(long long int)hexNumber
{
    char hexChar[20];
    sprintf(hexChar,"%llx", hexNumber);
    NSString *hexString = [NSString stringWithCString:hexChar encoding:NSUTF8StringEncoding];
    return hexString;
}

字符串的大小写转换

// 把字符串全部转化为小写
NSString *lowercaseString = [str lowercaseString];
NSString * lowercaseString = str.lowercaseString;

// 把字符串全部转化为大写
NSString *uppercaseString = [str uppercaseString];
NSString *uppercaseString = str.uppercaseString;

//开头大写,其余小写
NSString *capitalizedString =[str capitalizedString];

16进制字符串转数值

- (long long int)numberWithHexString:(NSString*)hexString
{
    const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];
    long long int hexNumber;
    sscanf(hexChar,"%llx", &hexNumber);
    return (long long int)hexNumber;
}

16进制字符串转NSData

//这个方法是从头开始取,如果字符串是奇数,最后一位会被舍弃
- (NSData *) stringToHexData:(NSString *)hexStr
{
    unsigned long len = [hexStr length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [hexStr length] / 2; i++) {
        byte_chars[0] = [hexStr characterAtIndex:i*2];
        byte_chars[1] = [hexStr characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}
//这个方法,如果字符串是奇数位,则第一位默认补零,再依次向后转换
- (NSData *)convertHexStrToData:(NSString *)str
{
    if (!str || [str length] == 0) {
        return nil;
    }
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:20];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        range.location += range.length;
        range.length = 2;
    }
    return hexData;
}
上一篇下一篇

猜你喜欢

热点阅读