Reputation: 55
I've been working on a calculator and I wanted to implement conversions from decimal to octal and from decimal to hexadecimal. I'm new to Xcode and Objective C, but I've managed to get a conversion from decimal to octal, it just doesn't seem to work with hexadecimal.
Here's the code I've written to convert a double to octal:
double result = 0;
...
double decToOct = [self popOperand];
NSString *oct = [NSString stringWithFormat:@"%llo", (long long)decToOct];
result = [oct doubleValue];
Using the same scheme (obviously that includes changing @"%llo"
with @"%llx"
) the conversion to hexadecimal works up to a certain point. It does numbers 0 through 9 just fine, but once it hits 10, it comes up as 0. To test, I also input 5395 and it displayed 1513, the desired result.
Because of this, I can only assume that for some reason my code does not want to input the actual letters of the hexadecimal values (e.g. 11 would convert to B but it shows up as 0) .
Any suggestions? Thanks in advance.
UPDATE:
In addition, I have also been using this to display the result
:
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:@"%g", result];
result
, as listed from the top, is an argument which is eventually returned here, to self.brain performOperation:operation
. This is supposed to handle the display of all operations, including: addition, multiplication, etc. but also octal and hexadecimal. Again, it works fine with octal, but not with hexadecimal.
Upvotes: 0
Views: 2554
Reputation: 16416
If you know your string only contains a valid decimal number then the simplest way would be:
NSString *dec = @"254";
NSString *hex = [NSString stringWithFormat:@"0x%lX",
(unsigned long)[dec integerValue]];
NSLog(@"%@", hex);
Upvotes: 0
Reputation: 186
Try this, May be it will help you. Please do let me know if i am wrong here:--->
NSString *decStr = @"11";
NSString *hexStr = [NSString stringWithFormat:@"%lX",
(unsigned long)[dec integerValue]];
NSLog(@"%@", hexStr);
Upvotes: 3