I’m trying to make an app to convert a decimal number into a binary number, but when I input the decimal number into a text field and have a button call the binaryConvert method, it continually returns 111111111111111111 (1 for every evaluation). Why is this??
- (NSString*)binaryConvert:(int)decNum {
int i = 1;
int value = 524288;
NSString * binary = @".";
while (i <= 19) {
if ((decNum/value) >= 1) {
binary = [binary stringByAppendingString:@"1"];
decNum -= value;
} else {
binary = [binary stringByAppendingString:@"0"];
}
value /= 2;
i++;
}
return binary;
}
- (IBAction)convertToBinary:(id)sender {
int decNum = (int)textField.text;
if ([textField.text length] > 6) {
answer.text = @"Too many numbers entered.";
} else {
answer.text = [self binaryConvert:decNum];
}
[textField resignFirstResponder];
}
answer is a label.
int decNum = (int)textField.text; // WRONG
Should be:
int decNum = [textField.text intValue];
// my previous wrong answer:
// decNum -= value should be done everytime; not only on if ((decNum/value) >= 1)