我想将普通的NSString转换为带有(我认为是)ASCII十六进制值的NSString,然后再将其转换回去。
我需要生成与以下Java方法相同的输出结果,但我似乎找不到在Objective-C中实现它的方法。我已经找到了一些在C和C ++中的例子,但我很难将它们融入我的代码中。
这里是我想要复制的Java方法:
/**
* 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);
}
更新: 感谢drawnonward在这里的答案,这是我编写用于创建十六进制NSString的方法。在char声明行上,它会给我一个“Initialization discards qualifiers from pointer target type”的警告,但它仍然可以工作。
- (NSString *)stringToHex:(NSString *)string
{
char *utf8 = [string UTF8String];
NSMutableString *hex = [NSMutableString string];
while ( *utf8 ) [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];
return [NSString stringWithFormat:@"%@", hex];
}
我还没有时间编写解码方法。当我有时间时,我会编辑此内容并将其发布给其他感兴趣的人。
更新2:所以我上面发布的方法实际上并没有输出我要找的内容。它不是以0-f格式输出十六进制值,而是输出了所有数字。我最终回到了这个问题并且编写了一个NSString分类,完全复制了我之前发布的Java方法。这是代码:
//
// 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] = {'\0','\0','\0'};
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
stringFromHex
方法的发现正是我也在寻找的。请问您从哪里得到这个方法,是否有教程可以参考?我想理解这个方法,但我自己无法分析它。谢谢。 - Melvin Lai