将Hex字符串转换为ASCII格式 [英] Convert Hex String to ASCII Format

查看:221
本文介绍了将Hex字符串转换为ASCII格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个十六进制字符串,如000000000100,我使用以下逻辑进行ASCII转换,我收到的输出只有1个字节(\ x01)但我希望输出为6字节格式为\\ \\ x00 \ x00 \ x00 \ x00 \ x01 \ x00

I have a Hex string like "000000000100" and I am using the following logic to do ASCII conversion, the output I am receiving is only 1 byte (\x01) But I want the output in the 6 byte format as \x00\x00\x00\x00\x01\x00

-(NSString*) decode
{
   string=@"000000000100";
   NSMutableString * newString = [[NSMutableString alloc]init];
  int i = 0;
  while (i < [string length])
  {
     NSString * hexChar = [string substringWithRange: NSMakeRange(i, 2)];
     int value = 0;
     sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
     [newString appendFormat:@"%c", (char)value];
     i+=2;
  }
return newString;

}

怎么做?

推荐答案

让我们首先直接解决您的错误:在您的代码中,您尝试将下一个字节添加到字符串中:

Let's first directly address your bug: In your code you attempt to add the next byte to your string with:

[newString appendFormat:@"%c", (char)value];

你的问题是%c 产生 nothing 如果该字符为null,那么您附加一个空字符串,并且当您发现最终得到一个包含单个字节的字符串时。

Your problem is that %c produces nothing if the character is a null, so you are appending an empty string and as you found end up with a string with a single byte in it.

您可以通过测试null并附加包含单个null的字符串来修复代码:

You can fix your code by testing for the null and appending a string containing a single null:

if (value == 0)
   [newString appendString:@"\0"]; // append a single null
else
   [newString appendFormat:@"%c", (char)value];

第二,这是这样做的吗?

Second, is this the way to do this?

其他答案已经向您展示了其他算法,它们可能比您的更有效,因为它们只转换为C字符串一次,而不是重复提取子字符串并单独转换每个字符串。

Other answers have shown you other algorithms, they might be more efficient than yours as they only convert to a C-String once rather than repeatedly extract substrings and convert each one individually.

当且仅当性能对您来说是一个真正的问题时,您可能希望考虑这样的基于C的解决方案。您清楚地知道如何使用 scanf ,但在这种简单的情况下,您可能希望查看 digittoint 和自己将两个十六进制数字转换为整数(第一个值为* 16 +第二个值)。

If and only if performance is a real issue for you you might wish to consider such C-based solutions. You clearly know how to use scanf, but in such a simple case as this you might want to look at digittoint and do the conversion of two hex digits to an integer yourself (value of first * 16 + value of second).

相反,如果你想避免使用C和 scanf 查看 NSScanner scanHexInt / scanHexLongLong - 如果您的字符串永远不会超过16位十六进制数字,您可以一次转换整个字符串,然后从字节为单位生成 NSString 得到的无符号64位整数。

Conversely if you'd like to avoid C and scanf look at NSScanner and scanHexInt/scanHexLongLong - if your strings are never longer than 16 hex digits you can convert the whole string in one go and then produce an NSString from the bytes of the resultant unsigned 64-bit integer.

HTH

这篇关于将Hex字符串转换为ASCII格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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