iOS 蓝牙命令数据格式转换,蓝牙返回数据解析

2019-11-29  本文已影响0人  前尘梦醒

1.蓝牙命令写入数据格式转换:

- (NSMutableData*)convertHexStrToData:(NSString*)str{

    if(!str || [strlength] ==0) {

        returnnil;

    }

    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];

    NSRangerange;

    if([strlength] %2==0) {

        range =NSMakeRange(0,2);

    }else{

        range =NSMakeRange(0,1);

    }

    for(NSIntegeri = range.location; i < [strlength]; i +=2) {

        unsignedintanInt;

        NSString*hexCharStr = [strsubstringWithRange:range];

        NSScanner*scanner = [[NSScanneralloc]initWithString:hexCharStr];

        [scannerscanHexInt:&anInt];

        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];

        [hexDataappendData:entity];

        range.location+= range.length;

        range.length=2;

    }

    returnhexData;

}

2.蓝牙数据解析:

- (NSString*)hexStringFromData:(NSData*)myD{

    Byte*bytes = (Byte*)[myDbytes];

    //下面是Byte 转换为16进制。

    NSString*hexStr=@"";

    for(inti=0;i<[myDlength];i++){

        NSString*newHexStr = [NSStringstringWithFormat:@"%x",bytes[i]&0xff];///16进制数

        if([newHexStrlength]==1)

            hexStr = [NSStringstringWithFormat:@"%@0%@",hexStr,newHexStr];

        else

            hexStr = [NSStringstringWithFormat:@"%@%@",hexStr,newHexStr];

    }

    NSLog(@"hex = %@",hexStr);

    returnhexStr;

}

上一篇 下一篇

猜你喜欢

热点阅读