博客> IOS 转换数据成蓝牙发送的十六进制数据
IOS 转换数据成蓝牙发送的十六进制数据
2017-11-21 22:44 评论:0 阅读:309 嗲吗够
ios 蓝牙数据 十六进制

1、如蓝牙发送颜色变化数据 -- 根据硬件需要的各种数据的其中一种转换方式,如下图,硬件需要8个数据:**10、20、30、40、50、60、70、80等* `+(NSData )colorFocusRGB:(NSMutableArray *)array{

Byte bytes[8];  
bytes[0] = (Byte)([array[0] intValue]);  
bytes[1] = (Byte)([array[1] intValue]);  
bytes[2] = (Byte)([array[2] intValue]);  
bytes[3] = (Byte)([array[3] intValue]);  
bytes[4] = (Byte)([array[4] intValue]);  
bytes[5] = (Byte)([array[5] intValue]);  
bytes[6] = (Byte)([array[6] intValue]);  
bytes[7] = (Byte)([array[7] intValue]);  

NSData *data = [NSData dataWithBytes:bytes length:8];  

return data;  

}

2、蓝牙发送颜色直接转换 -- 硬件需要的数据只需要RGB和Alpha +(NSData *)bleColorAlpha:(int)alpha andRed:(int)red andGreen:(int)green andBlue:(int)blue{

NSData * data = [[NSData alloc]init];  

NSString * colorStr = [NSString stringWithFormat:@"ctl:%d:%d:%d:%d:",alpha,red,green,blue];  
data = [colorStr dataUsingEncoding:NSUTF8StringEncoding];  

NSLog(@"调节颜色的值:%@",data);  
return data;  

}

3、发送十六进制的Str变化成data

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

NSLog(@"hexToBytes:data:%@",data);  
return data;  

}

4、将十进制转换成十六进制,其中0表示成00

+(NSString *)tenToHex:(long long int)tmpid

{

NSString *nLetterValue;  
NSString *str =@"";  
int ttmpig;  
for (int i = 0; i&lt;9; i++) {  
    ttmpig=tmpid;  
    tmpid=tmpid/16;  
    switch (ttmpig)  
    {  
        case 10:  
            nLetterValue =@"A";break;  
        case 11:  
            nLetterValue =@"B";break;  
        case 12:  
            nLetterValue =@"C";break;  
        case 13:  
            nLetterValue =@"D";break;  
        case 14:  
            nLetterValue =@"E";break;  
        case 15:  
            nLetterValue =@"F";break;  
        default:  
            nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];  
              ###
    }  
    str = [nLetterValue stringByAppendingString:str];  
    if (tmpid == 0) {  
        break;  
    }  
}  
//不够一个字节凑0  
if(str.length == 1){  
    return [NSString stringWithFormat:@"0%@",str];  
}else{  
    return str;  
}  

}
5、发送指定的命令到硬件,如0XFF、0XAA等

  • (NSData *)testData
    {
    unsigned char Buffer[9];
    Buffer[0] = 0x4A;
    Buffer[1] = 0x53;
    Buffer[2] = 0x02;
    Buffer[3] = 0x23;
    Buffer[4] = 0xAA;
    Buffer[5] = 0xBB;
    Buffer[6] = 0xCC;
    Buffer[7] = 0x36;
    Buffer[8] = 0x57;

    return [NSData dataWithBytes:Buffer length:9];
    }

收藏
0
sina weixin mail 回到顶部