Convert 0x001234AB to NSString "001234AB" - objective-c

I used Google, and Bing and SO, and I get literally hundreds of answers how to convert string to an integer, but cannot find a single example how to convert a number to a string in HEX base. And I need to convert thousands (into the same string) so a faster method is preferred.
int x = 0x001234ab;
NSString str;
<------- what should behere?
NSLog(str); // outputs "001234AB" or "001234ab"

NSLog(#"%x", x);
Or if you want it in string.
NSString *s = [NSString stringWithFormat:#"%x", x];
If you want leading zeros your format will look like this
#"%0yx"
where y is number of zeros (for your example 8).

Related

How to define a variable string format specifier

I have this line of code
// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: #"%.10Lg", valueX];
This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.
I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %# because %.10Lg is a format specifier by itself.
OK, I can create a bunch of strings like #"%.5Lg", #"%.8Lg", #"%.9Lg"... and switch that, but I wonder if there is another way...
There is, if you read the manual pages for format specifiers. You can replace the precision with *, which means it will get taken from a parameter instead.
int numDigits = 10;
NSString *value = [NSString stringWithFormat:#"%.*Lg", numDigits, valueX];
I couldn't find this in the core foundation reference, but I know that this is written in the man 3 printf man page.
Dietrich's answer is the simplest and therefore best. Note that even if there wasn't a built-in way to specify the number of digits with a parameter you could still have done it by first building your format string and then using it:
- (NSString *) stringFromValue: (long double) value digits: (int) digits; {
//First create a format string. Use "%%" to escape the % escape char.
NSString *formatString =[NSString stringWithFormat: #"%%.%dLg", digits];
return [NSString stringWithFormat: formatString, value];
}

What happened to Objective-C's "stringWithFormat:" method?

When I define
NSString *testString = [NSString stringWithFormat:#"%4d", 543210];
then testString is #"543210", instead of #"3210"
This used to work in Xcode v4.3.1 but now I upgraded to v4.6 and it stopped working.
Any ideas?
then testString is #"543210", instead of #"3210"
That's the correct behavior anyway. The %Nd format specifier doesn't limit the field with of the number being formatted - it only pads it with space if the field with is greater than the number of characters required to represent the number. If you got 3210 previously, that's erroneous.
If you want to format a number so at most its last four digits are printed, then you can do something like this:
NSString *numStr = [NSString stringWithFormat:#"%d", 543210]; // or whatever
if (numStr.length > 4) {
numStr = [numStr substringFromIndex:numStr.length - 4];
}
Another alternative, has the benefit of being short:
NSString *testString = [NSString stringWithFormat:#"%4d", 543210 % 10000];
The modulus operator % returns the remainder, so if you % 10000 you get the 4 least significant digits.

Padding a number in NSString

I have an int, for example say 45. I want to get NSString from this int padded with 4 zeroes. So the result would be : #"0045". Similar, if the int is 9, I want to get: #"0009".
I know I can count the number of digits, then subtract it from how many zeroes i want padded, and prepend that number to the string, but is there a more elegant way? Thanks.
Try this:
NSLog(#"%04d", 45);
NSLog(#"%04d", 9);
If it works, then you can get padded number with
NSString *paddedNumber = [NSString stringWithFormat:#"%04d", 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:#"%04d", 9];
Update
If you want to have arbitrary number you'd have to create a format for your format:
// create "%04d" format string
NSString *paddingFormat = [NSString stringWithFormat:#"%%0%dd", 4];
// use it for padding numbers
NSString *paddedNumber = [NSString stringWithFormat:paddingFormat, 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:paddingFormat, 9];
Update 2
Please see #Ibmurai's comment on how to properly pad a number with NSLog.
Excuse me for answering this question with an already accepted answer, but the answer (in the update) is not the best solution.
If you want to have an arbitrary number you don't have to create a format for your format, as IEEE printf supports this. Instead do:
NSString *paddedNumber = [NSString stringWithFormat:#"%0*d", 4, 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:#"%0*d", 4, 9];
While the other solution works, it is less effective and elegant.
From the IEEE printf specification:
A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision.
Swift version as Int extension (one might wanna come up with a better name for that method):
extension Int
{
func zeroPaddedStringValueForFieldWidth(fieldWidth: Int) -> String
{
return String(format: "%0*d", fieldWidth, self)
}
}
Examples:
print( 45.zeroPaddedStringValueForFieldWidth(4) ) // prints "0045"
print( 9.zeroPaddedStringValueForFieldWidth(4) ) // prints "0009"

is it possible to convert NSString into unichar

I have a NSString object and want to change it into unichar.
int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298
NSString *hex = [NSString stringWithFormat:#"0x%x", decimal]; // hex = 0x300a
NSString *chineseChar = [NSString stringWithFormat:#"%C", hex];
// This statement log a different Chinese char every time I run this code
NSLog(#"%#",chineseChar);
When I see the log, It gives different character every time when I run my code.
m I missing something...?
The %C format specifier takes a 16-bit Unicode character (unichar) as input, not an NSString. You're passing in an NSString, which is getting reinterpreted as an integer character; since the string can be stored at a different address in memory each time you run, you get that address as an integer, which is why you get a different Chinese character every time you run your code.
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET
How about -[NSString characterAtIndex:]? It wants a character index and returns a unichar.

Format string, integer with leading zeros

I want to convert an integer value to a string with leading zeroes (if necessary) such that the string has 3 total characters. For example, 5 would become "005", and 10 would become "010".
I've tried this code:
NSString* strName = [NSString stringWithFormat:#"img_00%d.jpg", i];
This partially works, but if i has the value of 10, for example, the result is img_0010.jpg, not img_010.jpg.
Is there a way to do what I want?
Use the format string "img_%03d.jpg" to get decimal numbers with three digits and leading zeros.
For posterity: this works with decimal numbers.
NSString *nmbrStr = #"0033620340000" ;
NSDecimalNumber *theNum = [[NSDecimalNumber decimalNumberWithString:nmbrStr]decimalNumberByAdding: [NSDecimalNumber one]] ;
NSString *fmtStr = [NSString stringWithFormat:#"%012.0F",[theNum doubleValue]] ;
Though this information is hard to find, it is actually documented here in the second paragraph under Formatting Basics. Look for the % character.
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html