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

后端 未结 9 1305
栀梦
栀梦 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条回答
  •  遥遥无期
    2020-12-03 12:51

    Here's an example decoder implemented on a category on NSString.

    #import 
    #import 
    #import 
    
    unsigned char strToChar (char a, char b)
    {
        char encoder[3] = {'\0','\0','\0'};
        encoder[0] = a;
        encoder[1] = b;
        return (char) strtol(encoder,NULL,16);
    }
    
    @interface NSString (NSStringExtensions)
    - (NSData *) decodeFromHexidecimal;
    @end
    
    @implementation NSString (NSStringExtensions)
    
    - (NSData *) decodeFromHexidecimal;
    {
        const char * bytes = [self cStringUsingEncoding: NSUTF8StringEncoding];
        NSUInteger length = strlen(bytes);
        unsigned char * r = (unsigned char *) malloc(length / 2 + 1);
        unsigned char * index = r;
    
        while ((*bytes) && (*(bytes +1))) {
            *index = strToChar(*bytes, *(bytes +1));
            index++;
            bytes+=2;
        }
        *index = '\0';
    
        NSData * result = [NSData dataWithBytes: r length: length / 2];
        free(r);
    
        return result;
    }
    
    @end
    

提交回复
热议问题