将十六进制数据字符串转换为 Objective C (cocoa) 中的 NSData [英] Convert hex data string to NSData in Objective C (cocoa)

查看:15
本文介绍了将十六进制数据字符串转换为 Objective C (cocoa) 中的 NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是相当新的 iPhone 开发者.构建一个应用程序,通过 TCP/IP 套接字连接将 RS232 命令发送到设备.我已经解决了通信部分,并且可以正常发送 ASCII 命令.这是我遇到问题的十六进制代码命令.

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 send ASCII commands fine. It's the hex code commands I'm having trouble with.

所以假设我有以下十六进制数据要发送(以这种格式):

So lets say I have the following hex data to send (in this format):

x1Cx02dx00x00x00xFFx7F

x1Cx02dx00x00x00xFFx7F

如何将其转换为我的 send 方法所期望的 NSData 对象?

How do I convert this into an NSData object, which my send method expects?

显然这不适用于此十六进制数据(但适用于标准 ascii 命令):

Obviously this does not work for this hex data (but does for standard ascii commands):

NSString *commandascii;
NSData *commandToSend;
commandascii = @"x1Cx02dx00x00x00xFFx7F";
commandToSend = [commandascii dataUsingEncoding:NSStringEncoding];

首先,一些 x 十六进制代码是转义字符,在 XCode 中编译时,我收到输入转换已停止..."警告.NSStringEncoding 显然也不适合这个十六进制字符串.

For a start, some of the x hex codes are escape characters, and I get an "input conversion stopped..." warning when compiling in XCode. And NSStringEncoding obviously isn't right for this hex string either.

所以我猜第一个问题是如何存储这个十六进制字符串,然后是如何转换为 NSData.

So the first problem is how to store this hex string I guess, then how to convert to NSData.

有什么想法吗?

推荐答案

NSStrings 中的十六进制代码,如00 05 22 1C EA 01 00 FF".'command' 是十六进制 NSString.

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] = {'','',''};
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);

这篇关于将十六进制数据字符串转换为 Objective C (cocoa) 中的 NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆