iOS 蓝牙-获取校验和
获取校验和方法
-(Byte)CalCheckSum2:(NSData*)data
{
Byte chksum=0;
Byte*byte=(Byte*)[databytes];
for(NSUInteger i=0;i<[datalength];i++)
{
chksum+=byte[I];
}
returnchksum;
}
我的需求:指令是13位byte数组,最后一位是前面十二位的校验和,第三四位是时间(24小时制)小时和分钟转换成的byte字节,其他的都是固定的指令。我的构造方法是
//防盗器 定时充电指令
-(void)onTimeChargeByBlueWith:(NSString*)timeStr
{
NSArray*array=[timeStr componentsSeparatedByString:@":"];
Byte onTimeChargeOrder[13]={0};
onTimeChargeOrder[0]=0xB9;
onTimeChargeOrder[1]=0x60;
onTimeChargeOrder[2]=[self getByteWithIntString:array[0]];
onTimeChargeOrder[3]=[self getByteWithIntString:array[1]];
onTimeChargeOrder[4]=0x00;
onTimeChargeOrder[5]=0x00;
onTimeChargeOrder[6]=0x00;
onTimeChargeOrder[7]=0x00;
onTimeChargeOrder[8]=0x00;
onTimeChargeOrder[9]=0x00;
onTimeChargeOrder[10]=0x00;
onTimeChargeOrder[11]=0x00;
onTimeChargeOrder[12]=[self CalCheckSum2:[NSData dataWithBytes:onTimeChargeOrder length:12]];
NSData*data=[NSData dataWithBytes:&onTimeChargeOrder length:sizeof(onTimeChargeOrder)];
NSLog(@"构造完的数据是 %@",data);//这里可以拿到data,然后对蓝牙的peripheral对象调用writeValue方法// [self.currPeripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
#pragmamark-----------工具方法----------------
-(Byte)getByteWithIntString:(NSString*)intString
{
inthourInt=[intString intValue];
Byte hourByte[4]={0};
hourByte[0]=(char)(hourInt>>24&0xff);
hourByte[1]=(char)((hourInt>>16)&0xff);
hourByte[2]=(char)((hourInt>>8)&0xff);
hourByte[3]=(char)((hourInt)&0xff);
return(char)((hourInt)&0xff);
}
// 获取校验和
-(Byte)CalCheckSum2:(NSData*)data
{
Byte chksum=0;
Byte*byte=(Byte*)[data bytes];
for(NSUInteger i=0;i<[data length];i++){
chksum+=byte[I];
}
returnchksum;
}
最后调用方法
[self onTimeChargeByBlueWith:@"13:45"];
得到的数据为
2017-03-11 11:23:21.211 test0227[92358:2093146] 构造完的数据是 <b9600d2d 00000000 00000000 53>