Objective-C中,NSString和Byte的转换
NSString*str=@"AA21f0c1762a3abc299c013abe7dbcc50001DD"怎么将里面的字符转换到Byte数组中,如下Bytebuffer...
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]; 展开
怎么将里面的字符转换到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]; 展开
1个回答
展开全部
NSString *str = @"AA21f0c1762a3abc299c013abe7dbcc50001DD";
NSData* bytes = [str dataUsingEncoding:NSUTF8StringEncoding];
Byte * myByte = (Byte *)[bytes bytes];
NSLog(@"myByte = %s",myByte);
NSData* bytes = [str dataUsingEncoding:NSUTF8StringEncoding];
Byte * myByte = (Byte *)[bytes bytes];
NSLog(@"myByte = %s",myByte);
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询