先上代码再说o( ̄︶ ̄)o
写命令的时候拼接用mutabledata拼接,不要用byte拼,这样处理会更简单一些
#pragma mark - check字段校验和
- (NSData *)checkFieldCheckout:(NSData *)originalData {
// data 转 16进制
NSString *originalStr = [requestTool hexStringFromData:originalData];
// 数组 每个字节分装
NSMutableArray *originalArr = [self getArrWithString:originalStr];
// 定义一个最后的需要的字段
uint8_t checkNum = 0x00;
// 每个字节转化成 Uint8_t 然后相加 最后得出一个需要的字节
for (NSInteger i = 0; i < originalArr.count; i++) {
NSString *str = [NSString stringWithFormat:@"0x%@",originalArr[i]];
const char *temChar = [str UTF8String];
int temW;
sscanf(temChar, "0x%2x",&temW);
checkNum += temW;
}
NSLog(@"%x", checkNum);
// 赋值到 自定义的 struct 这里可以不用
struct horse_check check;
check.CHECK = checkNum;
// 转化成data输出
NSData *checkNumData = [NSData dataWithBytes:&check length:1];
return checkNumData;
}
这里是里边用到的自定义的东西
struct horse_check {
uint8_t CHECK;
};
- (NSMutableArray *)getArrWithString:(NSString *)keysource {
NSMutableArray *keysourceArr = [NSMutableArray array];
for (NSInteger i = 0; i < keysource.length/2; i++) {
NSString *str = [keysource substringWithRange:NSMakeRange(2*i, 2)];
str = [NSString stringWithFormat:@"%@",str];
[keysourceArr addObject:str];
}
return keysourceArr;
}
/**
* data 转 16进制
*/
+ (NSString *)hexStringFromData:(NSData *)data
{
NSAssert(data.length > 0, @"data.length <= 0");
NSMutableString *hexString = [[NSMutableString alloc] init];
const Byte *bytes = data.bytes;
for (NSUInteger i=0; i<data.length; i++) {
Byte value = bytes[i];
Byte high = (value & 0xf0) >> 4;
Byte low = value & 0xf;
[hexString appendFormat:@"%x%x", high, low];
}
return hexString;
}
网友评论