Mi piacerebbe convertire un normale NSString in un NSString con i valori esadecimali ASCII (cosa presumo siano) e indietro.Come convertire una NSString in valori esadecimali
Ho bisogno di produrre lo stesso output dei metodi Java riportati di seguito, ma non riesco a trovare un modo per farlo in Objective-C. Ho trovato alcuni esempi in C e C++ ma ho avuto difficoltà a lavorarli nel mio codice.
Ecco i metodi Java che sto cercando di riprodurre:
/**
* 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);
}
Update: Grazie alla drawnonward di risposta qui è il metodo che ho scritto per creare le NSStrings esagonali. Mi dà un avvertimento "Inizializzazione rigetti di qualificatori dal tipo di puntatore" sulla riga della dichiarazione del carico, ma funziona.
- (NSString *)stringToHex:(NSString *)string
{
char *utf8 = [string UTF8String];
NSMutableString *hex = [NSMutableString string];
while (*utf8) [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];
return [NSString stringWithFormat:@"%@", hex];
}
Non ho ancora avuto il tempo di scrivere il metodo di decodifica. Quando lo faccio, lo modifico per postarlo per chiunque sia interessato.
Update2: Quindi il metodo che ho postato sopra in realtà non produce quello che sto cercando. Invece di emettere valori esadecimali nel formato 0-f, stava invece emettendo tutti i numeri. Finalmente sono tornato a lavorare su questo problema ed è stato in grado di scrivere una categoria per NSString che duplica esattamente i metodi Java che ho postato. Eccolo:
//
// 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
ho questo codice a casa. Lo posterò quando scendo dal lavoro a meno che qualcuno non mi picchi. –
Ciao, so che questo è un vecchio post. Ma ho incontrato il tuo problema che ho affrontato e sì. Le tue scoperte per il metodo 'stringFromHex' sono quelle che stavo cercando anche io. Posso sapere da dove ottieni questo metodo e c'è un tutorial su di esso? Mi piacerebbe capire quel metodo e non posso analizzarlo da solo. Grazie. –
Scusa è passato troppo tempo, non ricordo più. –