Convert hex data string to NSData in Objective C (cocoa)

后端 未结 9 1304
栀梦
栀梦 2020-12-03 11:55

fairly new iPhone developer here. Building an app to send RS232 commands to a device expecting them over a TCP/IP socket connection. I\'ve got the comms part down, and can s

9条回答
  •  -上瘾入骨i
    2020-12-03 12:51

    This is an old topic, but I'd like to add some remarks.

    • Scanning a string with [NSString characterAtIndex] is not very efficient. Get the C string in UTF8, then scan it using a *char++ is much faster.

    • It's better to allocate NSMutableData with capacity, to avoid time consuming block resizing. I think NSData is even better ( see next point )

    • Instead of create NSData using malloc, then [NSData dataWithBytes] and finally free, use malloc, and [NSData dataWithBytesNoCopy:length:freeWhenDone:]

    It also avoids memory operation ( reallocate, copy, free ). The freeWhenDone boolean tells the NSData to take ownership of the memory block, and free it when it will be released.

    • Here is the function I have to convert hex strings to bytes blocks. There is not much error checking on input string, but the allocation is tested.

    The formatting of the input string ( like remove 0x, spaces and punctuation marks ) is better out of the conversion function. Why would we lose some time doing extra processing if we are sure the input is OK.

    +(NSData*)bytesStringToData:(NSString*)bytesString
    {
        if (!bytesString || !bytesString.length) return NULL;
        // Get the c string
        const char *scanner=[bytesString cStringUsingEncoding:NSUTF8StringEncoding];
        char twoChars[3]={0,0,0};
        long bytesBlockSize = formattedBytesString.length/2;
        long counter = bytesBlockSize;
        Byte *bytesBlock = malloc(bytesBlockSize);
        if (!bytesBlock) return NULL;
        Byte *writer = bytesBlock;
        while (counter--) {
            twoChars[0]=*scanner++;
            twoChars[1]=*scanner++;
            *writer++ = strtol(twoChars, NULL, 16);
        }
        return[NSData dataWithBytesNoCopy:bytesBlock length:bytesBlockSize freeWhenDone:YES];
    }
    

提交回复
热议问题