首页 > 代码库 > How convert devicetoken (NSString) into NSData
How convert devicetoken (NSString) into NSData
deviceToken是个nsdata (nslog like this:<35b79913 2f94bf8d 3f7a863f 398410ca d6c61428 bae03de4 bf86b656 1b1042bf>
)
我把它转化为nsstring(35b79913 2f94bf8d 3f7a863f 398410ca d6c61428 bae03de4 bf86b656 1b1042bf)后怎么再转换为nsdata(要nslog 依然是:<35b79913 2f94bf8d 3f7a863f 398410ca d6c61428 bae03de4 bf86b656 1b1042bf>)
后面在老外的提醒下才想起来打印的那些字符对应的是十六进制字符串,不是bytes。糊涂了。。。所以问题就转化为了16进制字符串转化为nsdata的问题
-(NSData *) dataFromHexString:(NSString *) hexstr{ NSMutableData *data = [[NSMutableData alloc] init]; NSString *inputStr = [hexstr uppercaseString]; NSString *hexChars = @"0123456789ABCDEF"; Byte b1,b2; b1 = 255; b2 = 255; for (int i=0; i<hexstr.length; i++) { NSString *subStr = [inputStr substringWithRange:NSMakeRange(i, 1)]; NSRange loc = [hexChars rangeOfString:subStr]; if (loc.location == NSNotFound) continue; if (255 == b1) { b1 = (Byte)loc.location; }else { b2 = (Byte)loc.location; //Appending the Byte to NSData Byte *bytes = malloc(sizeof(Byte) *1); bytes[0] = ((b1<<4) & 0xf0) | (b2 & 0x0f); [data appendBytes:bytes length:1]; b1 = b2 = 255; } } return data;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。