2009-03-17 13 views
13

Estoy tratando de averiguar cómo convertir un NSInteger, digamos 56, a un NSString que es una representación binaria del valor original (int). Tal vez alguien conozca una técnica de formateo que pueda aceptar 56 y devolver "111000" dentro del Objetivo C. Gracias a todos.Cómo convertir NSInteger a un valor binario (cadena)

Respuesta

26

No hay un operador de formateo incorporado para hacer eso. Si quería convertirlo en una cadena hexadecimal, se podría hacer:

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

Para convertirla en una cadena binaria, usted tiene que construir por sí mismo:

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

de conseguir uno de esos errores amarillas si no lo hace 'NSMutableString * str = [NSMutableString stringWithFormat : @ ""]; ' –

4

Aproximadamente:

-(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

¿Qué pasa si la entrada es cero? – epatel

+0

Esto falla si la entrada es 0 (o de hecho si el último bit es 0), y también asigna y desasigna objetos de cadena N, donde N es el número de bits en el número. No muy eficiente. –

+0

Por lo tanto, aproximadamente. Pero buena captura. –

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; 
} 

empecé a partir de la versión de Adam Rosenfield, y modificar a:

  • añadir espacios entre los bytes
  • mango firmado enteros

Salida de ejemplo:

-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 
Cuestiones relacionadas