2009-03-17 9 views

Répondre

26

Il n'y a pas d'opérateur de formatage intégré pour faire cela. Si vous voulez convertir en une chaîne hexadécimale, vous pouvez faire:

NSString *str = [NSString stringWithFormat:@"%x", theNumber]; 

Pour le convertir en une chaîne binaire, vous devrez construire vous-même:

NSMutableString *str = [NSMutableString stringWithFormat:@""]; 
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1) 
{ 
    // Prepend "0" or "1", depending on the bit 
    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0]; 
} 
+1

Vous obtenez une de ces erreurs jaunes si vous ne le faites pas 'NSMutableString * str = [NSMutableString stringWithFormat : @ ""]; ' –

4

En gros:

-(void)someFunction 
{ 
    NSLog([self toBinary:input]); 
} 

-(NSString *)toBinary:(NSInteger)input 
{ 
    if (input == 1 || input == 0) { 
    return [NSString stringWithFormat:@"%d", input]; 
    } 
    else { 
    return [NSString stringWithFormat:@"%@%d", [self toBinary:input/2], input % 2]; 
    } 
} 
+1

Que faire si l'entrée est zéro? – epatel

+0

Cela échoue si l'entrée est 0 (ou en fait si le dernier bit est 0), et alloue et libère également N objets chaîne, où N est le nombre de bits dans le nombre. Pas très efficace. –

+0

D'où à peu près. Mais bonne prise. –

20
NSString * binaryStringFromInteger(int number) 
{ 
    NSMutableString * string = [[NSMutableString alloc] init]; 

    int spacing = pow(2, 3); 
    int width = (sizeof(number)) * spacing; 
    int binaryDigit = 0; 
    int integer = number; 

    while(binaryDigit < width) 
    { 
     binaryDigit++; 

     [string insertString:((integer & 1) ? @"1" : @"0")atIndex:0]; 

     if(binaryDigit % spacing == 0 && binaryDigit != width) 
     { 
      [string insertString:@" " atIndex:0]; 
     } 

     integer = integer >> 1; 
    } 

    return string; 
} 

Je suis parti de la version d'Adam Rosenfield, et modifié pour:

  • ajouter des espaces entre les octets
  • poignée entiers signés

Exemple de sortie:

-7   11111111 11111111 11111111 11111001 
7    00000000 00000000 00000000 00000111 
-1   11111111 11111111 11111111 11111111 
2147483647 01111111 11111111 11111111 11111111 
-2147483648 10000000 00000000 00000000 00000000 
0    00000000 00000000 00000000 00000000 
2    00000000 00000000 00000000 00000010 
-2   11111111 11111111 11111111 11111110 
Questions connexes