ios - 使用socket传输字符串,系统会自动将 NSString 转为 NSData 传输.
PHPz
PHPz 2017-04-17 17:30:49
0
1
329

本意是想传输一系列16进制的字符串.而NSData类型会将 NSString 转为16进制的 ASCII 码.有什么方法可以直接传输16进制的数据么.

PHPz
PHPz

学习是最好的投资!

全部回覆(1)
小葫芦

//寫一個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進位的資料啦

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板