本意是想传输一系列16进制的字符串.而NSData类型会将 NSString 转为16进制的 ASCII 码.有什么方法可以直接传输16进制的数据么.
高洛峰2017-04-17 17:32:49
//寫一個NSData型別資料
+(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;
}
補充一下:這裡傳進來的Str已經是16進制的數字。
比方說發送字串:JLBT 就應該先變成16進位:NSString * Str = @"4a4c4254";
然後你發出去的資料就是16進位的資料啦