最近在做项目的时候遇到这样一个需求,需要将十六进制的字符串转换成字节数组,通过Socket连接,调用硬件接口控制灯光的开关以及其他硬件的需求。
NSString *str = @"AA21f0c1762a3abc299c013abe7dbcc50001DD"
将里面的字符转换到Byte数组中,如下
Byte buffer[] = { 0xAA, 0x21, 0xf0, 0xc1, 0x76, 0x2a, 0x3a, ... , 0x01, 0xDD }
@interface NSString (NSStringHexToBytes)
-(NSData*) hexToBytes ;
@end
@implementation NSString (NSStringHexToBytes)
-(NSData*) hexToBytes {
NSMutableData* data = [NSMutableDatadata];
int idx;
for (idx = 0; idx+2 <= self.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [selfsubstringWithRange:range];
NSScanner* scanner = [NSScannerscannerWithString:hexStr];
unsignedint intValue;
[scanner scanHexInt:&intValue];
[data appendBytes:&intValue length:1];
}
return data;
}
@end
应用:
NSData *data = [str hexToBytes];
网友评论