首页 > 代码库 > 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;}