问题描述
我想将常规 NSString 转换为具有(我假设是)ASCII 十六进制值并返回的 NSString.
I'd like to convert a regular NSString into an NSString with the (what I assume are) ASCII hex values and back.
我需要产生与下面的 Java 方法相同的输出,但我似乎无法在 Objective-C 中找到一种方法来做到这一点.我在 C 和 C++ 中找到了一些示例,但我很难将它们融入我的代码中.
I need to produce the same output that the Java methods below do, but I can't seem to find a way to do it in Objective-C. I've found some examples in C and C++ but I've had a hard time working them into my code.
以下是我试图重现的 Java 方法:
Here are the Java methods I'm trying to reproduce:
/**
* Encodes the given string by using the hexadecimal representation of its UTF-8 bytes.
*
* @param s The string to encode.
* @return The encoded string.
*/
public static String utf8HexEncode(String s) {
if (s == null) {
return null;
}
byte[] utf8;
try {
utf8 = s.getBytes(ENCODING_UTF8);
} catch (UnsupportedEncodingException x) {
throw new RuntimeException(x);
}
return String.valueOf(Hex.encodeHex(utf8));
}
/**
* Decodes the given string by using the hexadecimal representation of its UTF-8 bytes.
*
* @param s The string to decode.
* @return The decoded string.
* @throws Exception If an error occurs.
*/
public static String utf8HexDecode(String s) throws Exception {
if (s == null) {
return null;
}
return new String(Hex.decodeHex(s.toCharArray()), ENCODING_UTF8);
}
更新:感谢drawonward 的回答,这里是我编写的用于创建十六进制NSStrings 的方法.它在 char 声明行上给我一个初始化丢弃来自指针目标类型的限定符"警告,但它有效.
Update: Thanks to drawnonward's answer here's the method I wrote to create the hex NSStrings. It gives me an "Initialization discards qualifiers from pointer target type" warning on the char declaration line, but it works.
- (NSString *)stringToHex:(NSString *)string
{
char *utf8 = [string UTF8String];
NSMutableString *hex = [NSMutableString string];
while ( *utf8 ) [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];
return [NSString stringWithFormat:@"%@", hex];
}
还没来得及写解码方法.当我这样做时,我会编辑它以将其发布给其他感兴趣的人.
Haven't had time to write the decoding method yet. When I do, I'll edit this to post it for anyone else interested.
Update2: 所以我上面发布的方法实际上并没有输出我正在寻找的东西.它不是以 0-f 格式输出十六进制值,而是输出所有数字.我终于重新开始解决这个问题,并且能够为 NSString 编写一个完全复制我发布的 Java 方法的类别.这是:
Update2: So the method I posted above actually doesn't output what I'm looking for. Instead of outputting hex values in 0-f format, it was instead outputting all numbers. I finally got back to working on this problem and was able to write a category for NSString that exactly duplicates the Java methods I posted. Here it is:
//
// NSString+hex.h
// Created by Ben Baron on 10/20/10.
//
@interface NSString (hex)
+ (NSString *) stringFromHex:(NSString *)str;
+ (NSString *) stringToHex:(NSString *)str;
@end
//
// NSString+hex.m
// Created by Ben Baron on 10/20/10.
//
#import "NSString+hex.h"
@implementation NSString (hex)
+ (NSString *) stringFromHex:(NSString *)str
{
NSMutableData *stringData = [[[NSMutableData alloc] init] autorelease];
unsigned char whole_byte;
char byte_chars[3] = {'','',''};
int i;
for (i=0; i < [str length] / 2; i++) {
byte_chars[0] = [str characterAtIndex:i*2];
byte_chars[1] = [str characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[stringData appendBytes:&whole_byte length:1];
}
return [[[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding] autorelease];
}
+ (NSString *) stringToHex:(NSString *)str
{
NSUInteger len = [str length];
unichar *chars = malloc(len * sizeof(unichar));
[str getCharacters:chars];
NSMutableString *hexString = [[NSMutableString alloc] init];
for(NSUInteger i = 0; i < len; i++ )
{
[hexString appendString:[NSString stringWithFormat:@"%x", chars[i]]];
}
free(chars);
return [hexString autorelease];
}
@end
推荐答案
对于 Java 的这些行
For these lines of Java
utf8 = s.getBytes(ENCODING_UTF8);
new String(decodedHexString, ENCODING_UTF8);
Objective-C 的等价物是
Objective-C equivalents would be
utf8 = [s UTF8String];
[NSString initWithUTF8String:decodedHexString];
用字符串的十六进制表示生成一个 NSString:
To make an NSString with the hexadecimal representation of a character string:
NSMutableString *hex = [NSMutableString string];
while ( *utf8 ) [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];
您必须制作自己的 decodeHex 函数.只需从字符串中提取两个字符,如果它们有效,则向结果添加一个字节.
You will have to make your own decodeHex function. Just pull two characters out of the string and, if they are valid, add a byte to the result.
这篇关于如何将 NSString 转换为十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!