本意是想传输一系列16进制的字符串.而NSData类型会将 NSString 转为16进制的 ASCII 码.有什么方法可以直接传输16进制的数据么.
高洛峰2017-04-17 17:32:49
//Write an NSData type data
+(NSMutableData)HexStringToData:(NSString)str{
NSString *command = str;
command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
NSMutableData *commandToSend= [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {'rrreee','rrreee','rrreee'};
int i;
for (i=0; i < [command length]/2; i++) {
byte_chars[0] = [command characterAtIndex:i*2];
byte_chars[1] = [command characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[commandToSend appendBytes:&whole_byte length:1];
}
return commandToSend;
}
To add: the Str passed in here is already a hexadecimal number.
For example, when sending a string: JLBT, it should first be converted into hexadecimal: NSString * Str = @"4a4c4254";
Then the data you send will be hexadecimal data