recherche

Maison  >  Questions et réponses  >  le corps du texte

ios - 使用socket传输字符串,系统会自动将 NSString 转为 NSData 传输.

本意是想传输一系列16进制的字符串.而NSData类型会将 NSString 转为16进制的 ASCII 码.有什么方法可以直接传输16进制的数据么.

PHPzPHPz2887 Il y a quelques jours331

répondre à tous(1)je répondrai

  • 高洛峰

    高洛峰2017-04-17 17:32:49

    //Écrire une donnée de type NSData
    (NSMutableData)HexStringToData:(NSString)str{

    
    NSString *command = str;
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'rrreee','rrreee','rrreee'};
    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];
    }
    return commandToSend;

    }
    À ajouter : le Str transmis ici est déjà un nombre hexadécimal.
    Par exemple, lors de l'envoi d'une chaîne : JLBT, elle doit d'abord être convertie en hexadécimal : NSString * Str = @"4a4c4254";
    Ensuite, les données que vous envoyez seront des données hexadécimales

    répondre
    0
  • Annulerrépondre