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

后端 未结 9 1333
栀梦
栀梦 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:40

    Code for hex in NSStrings like "00 05 22 1C EA 01 00 FF". 'command' is the hex NSString.

    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    for (int i = 0; i < ([command length] / 2); i++) {
        byte_chars[0] = [command characterAtIndex:i*2];
        byte_chars[1] = [command characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [commandToSend appendBytes:&whole_byte length:1]; 
    }
    NSLog(@"%@", commandToSend);
    

提交回复
热议问题