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

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

PHPz
PHPz

学习是最好的投资!

reply all(1)
小葫芦

//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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template