I want to convert decimal number in binary number. I'm using this method:
- (NSMutableString*)intStringToBinary:(long long)element{
NSMutableString *str = [[NSMutableString alloc] initWithString:@""];
for(NSInteger numberCopy = element; numberCopy > 0; numberCopy >>= 1)
{
[str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
return str;
}
everything is going fine if the number "element" is >0. If the number is <0 there is the problem. For examle the method can't convert the number "-1". What can i do to solve the problem? Thanks in advance!!
You need an extra bit for the sign.
Example:
1xxxx
represents the binary number+ xxxx
.0yyyy
represents the binary number- yyyy
.