Je voudrais convertir un NSString régulier en NSString avec les valeurs hexadécimales ASCII (ce que je suppose être) et inversement.Comment convertir un NSString en valeurs hexadécimales
J'ai besoin de produire la même sortie que les méthodes Java ci-dessous, mais je n'arrive pas à trouver un moyen de le faire en Objective-C. J'ai trouvé quelques exemples en C et C++ mais j'ai eu du mal à les intégrer dans mon code.
Voici les méthodes Java, je suis en train de reproduire:
/**
* 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);
}
Mise à jour: Merci à de drawnonward réponse ici est la méthode que j'ai écrit pour créer les NSStrings hexagonaux. Il me donne un avertissement "Initialisation rejette les qualificatifs de type cible de pointeur" sur la ligne de déclaration char, mais cela fonctionne.
- (NSString *)stringToHex:(NSString *)string
{
char *utf8 = [string UTF8String];
NSMutableString *hex = [NSMutableString string];
while (*utf8) [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];
return [NSString stringWithFormat:@"%@", hex];
}
N'a pas eu le temps d'écrire la méthode de décodage pour le moment. Quand je le ferai, je l'éditerai pour l'afficher pour toute personne intéressée.
Update2: La méthode que j'ai affichée ci-dessus ne produit donc pas ce que je recherche. Au lieu de sortir des valeurs hexadécimales au format 0-f, il a plutôt émis tous les nombres. J'ai finalement travaillé sur ce problème et j'ai pu écrire une catégorie pour NSString qui duplique exactement les méthodes Java que j'ai publiées. Ici, il est:
//
// 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
Je le code à la maison. Je l'afficherai quand je quitterai le travail à moins que quelqu'un ne me batte dessus. –
Salut, je sais que c'est un vieux post. Mais je suis tombé sur votre problème auquel j'ai fait face et oui. Vos résultats pour la méthode 'stringFromHex' sont ce que je recherchais aussi. Puis-je savoir d'où provient cette méthode et y a-t-il un tutoriel? Je voudrais comprendre cette méthode, et je ne peux pas l'analyser par moi-même. Merci. –
Désolé, ça fait trop longtemps, je ne m'en souviens plus. –