Decimal to binary conversion

I want to convert decimal to binary number. I am 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 goes well, if the number "element"> 0. If the number <0, then the problem. For example, the method cannot convert the number "-1". What can I do to solve the problem? Thanks in advance!

+4
source share
2 answers

You need an extra bit for the character.

Example:

1xxxx represents the binary number + xxxx .

0yyyy represents a binary number - yyyy .

+2
source

Here's how to do it in Python using the Wallar algorithm. Input and output are lists.

 from math import * def baseExpansion(n,c,b): j = 0 base10 = sum([pow(c,len(n)-k-1)*n[k] for k in range(0,len(n))]) while floor(base10/pow(b,j)) != 0: j = j+1 return [floor(base10/pow(b,jp)) % b for p in range(1,j+1)] 
-1
source

All Articles