Estoy tratando de convertir un Hex NSString a NSData (estoy usando el siguiente código adjunto). El siguiente es el resultado:

<00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000>

que se ve totalmente irrelevante para mí. Cualquier idea/sugerencia acerca de dónde va mal?

NSString *strData = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";

NSLog(@"string Data length is %d",[strData length]);

NSMutableData *commandToSend= [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[2];
int i;
for (i=0; i < [strData length]/2; i++) {

    byte_chars[0] = [strData characterAtIndex:i*2];
    byte_chars[1] = [strData characterAtIndex:i*2+1];
    whole_byte = strtol(byte_chars, NULL, [strData length]);
    [commandToSend appendBytes:&whole_byte length:1]; 
}
NSLog(@"%@", commandToSend);    
  • No debe pasar de 16 a strtol?

4 Comentarios

  1. 65
    NSString *command = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";
    
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'
    NSString *command = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [command length]/2; i++) {
    byte_chars[0] = [command characterAtIndex:i*2];
    byte_chars[1] = [command characterAtIndex:i*2+1];
    whole_byte = strtol(byte_chars, NULL, 16);
    [commandToSend appendBytes:&whole_byte length:1]; 
    }
    NSLog(@"%@", commandToSend);
    '
    ,'
    NSString *command = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [command length]/2; i++) {
    byte_chars[0] = [command characterAtIndex:i*2];
    byte_chars[1] = [command characterAtIndex:i*2+1];
    whole_byte = strtol(byte_chars, NULL, 16);
    [commandToSend appendBytes:&whole_byte length:1]; 
    }
    NSLog(@"%@", commandToSend);
    '
    ,'
    NSString *command = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [command length]/2; i++) {
    byte_chars[0] = [command characterAtIndex:i*2];
    byte_chars[1] = [command characterAtIndex:i*2+1];
    whole_byte = strtol(byte_chars, NULL, 16);
    [commandToSend appendBytes:&whole_byte length:1]; 
    }
    NSLog(@"%@", commandToSend);
    '
    }; int i; for (i=0; i < [command length]/2; i++) { byte_chars[0] = [command characterAtIndex:i*2]; byte_chars[1] = [command characterAtIndex:i*2+1]; whole_byte = strtol(byte_chars, NULL, 16); [commandToSend appendBytes:&whole_byte length:1]; } NSLog(@"%@", commandToSend);
    • lo que los resultados que se están obteniendo?
    • su devuelve <72ff63ce a198b3ed ba8f7e0c 23acc345 050187a0 cde5a987 2cbab091 ab73e553>
    • perfecto gracias!
    • uno de los más ques whole_byte = strtol(byte_chars, NULL, 16); ¿por qué el tercer parámetro es pasado 16 Constante?
    • 16 como en la base 16 (es decir, Hex)
    • Bonita respuesta. Útil para la conversión de NSData deviceToken descripciones de nuevo en NSData.
    • Esto requiere que command tienen una longitud igual, ¿verdad?
    • como se ve en la respuesta que estamos recibiendo la misma respuesta que hemos dado de la cadena a convertir . ? pero, ¿cómo convertir los datos de cadena en informativos uno ? me refiero a después de la exploración de BLE dispositivo , tengo los datos de anuncio como » kCBAdvDataManufacturerData = <ffff0215 e84a40af 7b8de88d 4a7b40af afe84a40 40af7b8d c3>; ` este . así que ahora a partir de este , cómo convertir ,con el fin de acceder a sus datos . se supone que debo averiguar de Mayor a Menor TxPower de este dado de datos ,. ¿cómo podemos hacer esto ? @NikunjJadav
    • incluso me he planteado la pregunta de este [stackoverflow.com/questions/45854508/… . por favor, mire en él y me guía a través de ella . gracias .

  2. 29

    Aquí es otro método que también se ocupa de los principales <, detrás de la > y espacios incrustados como

    <9dc69faf a7434ba9 aef57f5c 365d571f 4c3753c4 ae13db42 57d184ca e00246c5>

    Código:

    + (NSData *)dataFromHexString:(NSString *)string
    {
        string = [string lowercaseString];
        NSMutableData *data= [NSMutableData new];
        unsigned char whole_byte;
        char byte_chars[3] = {'
    + (NSData *)dataFromHexString:(NSString *)string
    {
    string = [string lowercaseString];
    NSMutableData *data= [NSMutableData new];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i = 0;
    int length = string.length;
    while (i < length-1) {
    char c = [string characterAtIndex:i++];
    if (c < '0' || (c > '9' && c < 'a') || c > 'f')
    continue;
    byte_chars[0] = c;
    byte_chars[1] = [string characterAtIndex:i++];
    whole_byte = strtol(byte_chars, NULL, 16);
    [data appendBytes:&whole_byte length:1];
    }
    return data;
    }
    '
    ,'
    + (NSData *)dataFromHexString:(NSString *)string
    {
    string = [string lowercaseString];
    NSMutableData *data= [NSMutableData new];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i = 0;
    int length = string.length;
    while (i < length-1) {
    char c = [string characterAtIndex:i++];
    if (c < '0' || (c > '9' && c < 'a') || c > 'f')
    continue;
    byte_chars[0] = c;
    byte_chars[1] = [string characterAtIndex:i++];
    whole_byte = strtol(byte_chars, NULL, 16);
    [data appendBytes:&whole_byte length:1];
    }
    return data;
    }
    '
    ,'
    + (NSData *)dataFromHexString:(NSString *)string
    {
    string = [string lowercaseString];
    NSMutableData *data= [NSMutableData new];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i = 0;
    int length = string.length;
    while (i < length-1) {
    char c = [string characterAtIndex:i++];
    if (c < '0' || (c > '9' && c < 'a') || c > 'f')
    continue;
    byte_chars[0] = c;
    byte_chars[1] = [string characterAtIndex:i++];
    whole_byte = strtol(byte_chars, NULL, 16);
    [data appendBytes:&whole_byte length:1];
    }
    return data;
    }
    '
    }; int i = 0; int length = string.length; while (i < length-1) { char c = [string characterAtIndex:i++]; if (c < '0' || (c > '9' && c < 'a') || c > 'f') continue; byte_chars[0] = c; byte_chars[1] = [string characterAtIndex:i++]; whole_byte = strtol(byte_chars, NULL, 16); [data appendBytes:&whole_byte length:1]; } return data; }

    Esto se basa en la respuesta de @Nikunj R. Jadav

  3. 7

    Que esto podría ser más útil, Apple ha compartido un NSData categoría.

    NSData+HexString.m

    El código es:

    @implementation NSData (HexString)
    
    //Not efficent
    +(id)dataWithHexString:(NSString *)hex
    {
        char buf[3];
        buf[2] = '
    @implementation NSData (HexString)
    //Not efficent
    +(id)dataWithHexString:(NSString *)hex
    {
    char buf[3];
    buf[2] = '\0';
    NSAssert(0 == [hex length] % 2, @"Hex strings should have an even number of digits (%@)", hex);
    unsigned char *bytes = malloc([hex length]/2);
    unsigned char *bp = bytes;
    for (CFIndex i = 0; i < [hex length]; i += 2) {
    buf[0] = [hex characterAtIndex:i];
    buf[1] = [hex characterAtIndex:i+1];
    char *b2 = NULL;
    *bp++ = strtol(buf, &b2, 16);
    NSAssert(b2 == buf + 2, @"String should be all hex digits: %@ (bad digit around %d)", hex, i);
    }
    return [NSData dataWithBytesNoCopy:bytes length:[hex length]/2 freeWhenDone:YES];
    }
    @end
    '
    ; NSAssert(0 == [hex length] % 2, @"Hex strings should have an even number of digits (%@)", hex); unsigned char *bytes = malloc([hex length]/2); unsigned char *bp = bytes; for (CFIndex i = 0; i < [hex length]; i += 2) { buf[0] = [hex characterAtIndex:i]; buf[1] = [hex characterAtIndex:i+1]; char *b2 = NULL; *bp++ = strtol(buf, &b2, 16); NSAssert(b2 == buf + 2, @"String should be all hex digits: %@ (bad digit around %d)", hex, i); } return [NSData dataWithBytesNoCopy:bytes length:[hex length]/2 freeWhenDone:YES]; } @end
    • la memoria asignada dinámicamente por llamar a malloc() en … no es accesible después de la línea …. > return [NSData dataWithBytesNoCopy:bytes de longitud:[hex longitud]/2 freeWhenDone:YES];
  4. 0

    Veo a varios de solución han sido post sólo es capaz de convertir la cadena con longitud.

    Así que aquí está mi solución, que también capaz de devolver datos correctos si la cadena es de longitud impar como este «DBA» se convirtió en datos, como los del este «\x0D\xBA»

    + (NSData *)dataFromHexString:(NSString *) string {
        if([string length] % 2 == 1){
            string = [@"0"stringByAppendingString:string];
        }
    
        const char *chars = [string UTF8String];
        int i = 0, len = (int)[string length];
    
        NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
        char byteChars[3] = {'
    + (NSData *)dataFromHexString:(NSString *) string {
    if([string length] % 2 == 1){
    string = [@"0"stringByAppendingString:string];
    }
    const char *chars = [string UTF8String];
    int i = 0, len = (int)[string length];
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    while (i < len) {
    byteChars[0] = chars[i++];
    byteChars[1] = chars[i++];
    wholeByte = strtoul(byteChars, NULL, 16);
    [data appendBytes:&wholeByte length:1];
    }
    return data;
    }
    '
    ,'
    + (NSData *)dataFromHexString:(NSString *) string {
    if([string length] % 2 == 1){
    string = [@"0"stringByAppendingString:string];
    }
    const char *chars = [string UTF8String];
    int i = 0, len = (int)[string length];
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    while (i < len) {
    byteChars[0] = chars[i++];
    byteChars[1] = chars[i++];
    wholeByte = strtoul(byteChars, NULL, 16);
    [data appendBytes:&wholeByte length:1];
    }
    return data;
    }
    '
    ,'
    + (NSData *)dataFromHexString:(NSString *) string {
    if([string length] % 2 == 1){
    string = [@"0"stringByAppendingString:string];
    }
    const char *chars = [string UTF8String];
    int i = 0, len = (int)[string length];
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    while (i < len) {
    byteChars[0] = chars[i++];
    byteChars[1] = chars[i++];
    wholeByte = strtoul(byteChars, NULL, 16);
    [data appendBytes:&wholeByte length:1];
    }
    return data;
    }
    '
    }; unsigned long wholeByte; while (i < len) { byteChars[0] = chars[i++]; byteChars[1] = chars[i++]; wholeByte = strtoul(byteChars, NULL, 16); [data appendBytes:&wholeByte length:1]; } return data; }

Dejar respuesta

Please enter your comment!
Please enter your name here