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

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

问题描述

相当新的iPhone开发者在这里。构建应用程序以将RS232命令发送到期望通过TCP / IP套接字连接的设备。我有comms部分,并可以发送ASCII命令罚款。这是我遇到麻烦的十六进制代码命令。



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



\x1C\x02d\x00\x00\x00\xFF\x7F



如何转换显然这对于​​这个十六进制数据不起作用(但是对于标准的ascii命令):






$ b

  NSString * commandascii; 
NSData * commandToSend;
commandascii = @\x1C\x02d\x00\x00\x00\xFF\x7F;
commandToSend = [commandascii dataUsingEncoding:NSStringEncoding];

一开始,一些\x十六进制代码是转义字符,输入转换停止...在XCode中编译时出现警告。和NSStringEncoding显然是不正确的这个十六进制字符串。



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



任何想法?

解决方案

NSStrings中的十六进制代码,例如00 05 22 1C EA 01 00 FF。 'command'是十六进制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);


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):

\x1C\x02d\x00\x00\x00\xFF\x7F

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

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

NSString *commandascii;
NSData *commandToSend;
commandascii = @"\x1C\x02d\x00\x00\x00\xFF\x7F";
commandToSend = [commandascii dataUsingEncoding: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.

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

Any ideas?

解决方案

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);

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

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