上一篇已经介绍过蓝牙连接的具体步骤,其中重要的就是数据的写入和读取,数据的写入需要根据<蓝牙协议>(这个协议硬件开发的会给)的规则来写入.
其中这里面有个需要计算的就是checkSUM(校验和).不懂什么是校验和的可以自行百度下,这里就不多赘述了直接上代码了.
//求累加和(校验和)(CHECKSUM)的求法
- (NSData *)getCheckSum:(NSData *)byteStr{
int length = (int)byteStr.length;
// NSData *data = [self hexToBytes:byteStr];
Byte *bytes = (unsigned char *)[byteStr bytes];
Byte sum = 0;
for (int i = 0; i<length; i++) {
sum += bytes[i];
}
int sumT = sum;
int at = 256 - sumT;
printf("校验和:%d\n",at);
printf("累加和:%d\n",sumT);
if (at == 256) {
at = 0;
}
NSString *str = [NSString stringWithFormat:@"%@",[self ToHex:sumT]];
return [self hexToBytes:str];
}
//将十进制转化为十六进制
- (NSString *)ToHex:(int)tmpid
{
NSString *nLetterValue;
NSString *str =@"";
int ttmpig;
for (int i = 0; i<9; i++) {
ttmpig=tmpid%16;
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;
}
}
//NSLog(@"16进制是:%@",str);
//不够一个字节凑0
if(str.length == 1){
return [NSString stringWithFormat:@"0%@",str];
}else{
return str;
}
}
- (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];
}
return data;
}
//字符串转为NSData(非编码):
- (NSData *)convertHexStrToData:(NSString *)str {
if (!str || [str length] == 0) {
return nil;
}
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
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;
}
// NSLog(@"hexdata: %@", hexData);
return hexData;
}