Convert NSNumber to hex string with 16 digits - iphone

I have to convert an NSNumber to a hex string like follows:
return [NSString stringWithFormat:#"%llX", self.unsignedLongLongValue];
Unfortunately, this will sometimes give me string like 93728A166D1A287 where they should be 093728A166D1A287, depending on the number.
Hint: the leading 0.
I've also tried it with:
return [NSString stringWithFormat:#"%16.llX", self.unsignedLongLongValue];
without success.
I could do something like this, but that just sucks:
- (NSString *)hexValue {
NSString *hex = [NSString stringWithFormat:#"%llX", self.unsignedLongLongValue];
NSUInteger digitsLeft = 16 - hex.length;
if (digitsLeft > 0) {
NSMutableString *zeros = [[NSMutableString alloc] init];
for (int i = 0; i < digitsLeft; i++) [zeros appendString:#"0"];
hex = [zeros stringByAppendingString:hex];
}
return hex;
}
So finally my question, is there a way to enforce the string to be 16 characters?

If you need to zero-pad your hex numbers, use zero in front of the format specifier, like this:
return [NSString stringWithFormat:#"%016llX", self.unsignedLongLongValue];
This should take care of formatting your number with 16 digits, regardless of how many "meaningful" digits the number has.
Here is a demo of this format string in plain C (this part is shared between the two languages).

Use:
return [NSString stringWithFormat:#"%016llX", self.unsignedLongLongValue];
Which sets leading 0 and the length of the output string.

Related

Recognizing few integers in NSString

I am receiving a string from server in this format:
0_1_2_3
My task is to select for digits from this string to fill four labels with them.
First idea was:
NSString *res1 = [result substringWithRange:NSMakeRange(0, 1)];
[firstLabel setText:res1];
four times with appropriate labels.
But operation will repeats many times and every time I will receive a string with increased digit values. So when every digit be a decimal this code will not work. So how can I track every digit independently from their length in a proper way?
NSString comes with a convenience method called -componentsSeparatedByString:
NSString *myString = #"0_1_2_3";
NSArray *myDigitStrings = [myString componentsSeparatedByString:#"_"];
/* access digit strings from myDigitStrings array by index or fast enumeration... */
for (NSString *myDigitString in myDigitStrings)
NSLog(#"digit string: %#", myDigitString);

Why is my NSRange always 0?

I want to implement a delete key for my calculator app. My pseudocode for this was:
foo = length of current number
bar = length of current number-1
current number = current number with character at index (foo-bar) removed
To do this in objective-c I have tried to implement this using the NSRange function as well as the StringbyappendingString method:
- (IBAction)DelPressed {
if ([self.display.text length] >=2)
{
int len = [self.display.text length];//Length of entire display
//Add to the brainlong printing out the length of the entire display
self.brainlog.text = [NSString stringWithFormat:#"Len is %g",len];
int le = ([self.display.text length]-1);//Length of entire display - 1
NSString *lestring = [NSString stringWithFormat:#"LE is %g",le];
//Add to the brainlog printing out the length of the display -1
self.brainlog.text = [self.brainlog.text stringByAppendingString:lestring];
NSRange range = NSMakeRange(le, len);//range only includes the last character
self.display.text = [self.display.text stringByReplacingCharactersInRange:range withString:#" "];//Replace the last character with whitespace
}
The output to brainlog (ie the length of both le and len) is:
Len is -1.99164 Le is -1.99164
Hard to see, but here's an image of the number I input to the calculator using the iOS simulator:
I have tried to change the value of le (ie making it the length of the display -3 or -5 etc) and both le and len are still the same.
I have also tried to make le in reference to len:
int len = [self.display.text length];//Length of entire display
//Add to the brainlong printing out the length of the entire display
self.brainlog.text = [NSString stringWithFormat:#"Len is %g",len];
int le = len-1;
But the values of the two are still the same. How can I use NSRange to delete the last character of the display?
Edit: Using Dustin's fix, I now have reduced a rather lengthy function into 6 lines of code:
-(IBAction)DelPressed{
if ([self.display.text length] >=2)
{
self.display.text = [self.display.text substringToIndes:[self.display.text length] -1];
}
}
Use substring instead; it's much better if all you want to do is remove the last character.
More specifically, substringToIndex(/*length-1*/)
Check this reference out if you need to do other things with strings

objective-c stringvalue from double

I have the following code:
double d1 = 12.123456789012345;
NSString *test1 = [NSString stringWithFormat:#"%f", d1]; // string is: 12.123457
NSString *test1 = [NSString stringWithFormat:#"%g", d1]; // string is: 12.1235
How do I get a string value that is exactly the same as d1?
It may help you to take a look at Apple's guide to String Format Specifiers.
%f 64-bit floating-point number
%g 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise
Also read up on floating point (in)accuracy, and, of course What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you really want the string to match the double exactly, then use NSString to encode it and call doubleValue when you want the value. Also take a look at NSNumberFormatter.
How about
NSString *test1 = [NSString stringWithFormat:#"%.15f", d1];
Or simply go for the double as
NSString *test1 = [NSString stringWithFormat:#"%lf", d1];

converting an int to a string in Objective-C while preserving '0'

I am trying to convert an int to a string in objective-C.
I read the other questions on SO about converting ints to strings, and I tried this method in my code:
-(void)setCounter:(int)count
{
counterText.text = [NSString stringWithFormat:#"%d",count];
}
However, if I want to display a number like '01' the 0 is taken out of the conversion and only '1' is displayed. Is there a workaround?
There is no such number as 01. If you write
int count = 01;
it is compiled equivalently to
int count = 1;
In fact, be careful: 07 is equivalent to 7, but 011 is equivalent to 9!
What you can do is ask stringWithFormat: to give you the zero-padding:
[NSString stringWithFormat:#"%02d",count]
should give you "02" if count is 2. To deconstruct it:
% - interpolate the next value here
0 - pad it to the width by placing zeroes on the left side
2 - width is 2 characters
d - it will be an integer. Do it now.
If you want a different format to the one shown, use it:
counterText.text = [NSString stringWithFormat:#"%02d",count];
There are a huge range of possibilities with the format string.
if any number start from 0 then Its a octal representation (0 - 7). you can add zero explictly using below line.
counterText.text = [NSString stringWithFormat:#"0%d",count];
Check out..
NSNumber +numberWithInt
and then:
NSNumberFormatter -setMinimumIntegerDigits
and then get the string representation with:
NSString -stringFromNumber

Removing characters after the decimal point for a double

How can I remove the all the characters after the decimal point.
Instead of 7.3456, I would just like 7.
This is what I do to get the number so far with decimal places.
[NSString stringWithFormat:#" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];
Many Thanks,
-Code
You can specify what you want using format string :
[NSString stringWithFormat:#" %.0f : %.0f", (audioPlayer.currentTime),
(audioPlayer.duration)];
If you want this for display, use an NSNumberFormatter:
double sevenpointthreefourfivesix = 7.3456;
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithDouble:sevenpointthreefourfivesix]]);
2011-12-20 20:19:48.813 NoDecimal[55110:903] 7
If you want a value without the fractional part, use round(). If you want the closest integer value not greater than the original value, use floor().
floorf() is the function you're looking for.
you are after
[NSString stringWithFormat:#" %.00f : %.00f",(audioPlayer.currentTime),(audioPlayer.duration) ];
When formatting float you can tell the precision by the number before the f
Cast to int:
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime),(int)(audioPlayer.duration) ];
Casting like this always rounds down (eg: just removes everything after the decimal place). This is what you asked for.
In the case of rounding to the NEAREST whole number you want to add 0.5 to the number
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime+0.5f),(int)(audioPlayer.duration+0.5f) ];
This will round to the nearest whole number. eg: 1.2 becomes 1.7 and casting to int makes 1. 3.6 becomes 4.1 and casting makes 4. :)
Why not just cast the audioPlayer.currentTime to an integer before you use stringWithFormat?
[NSString stringWithFormat:#"%d", (int)(audioPlayer.currentTime)];
All you need to do is type-cast the double to an int, like so: int currentTime_int = (int)audioPlayer.currentTime;.
You can use this same approach for the other variable.
Many of the shorter answers here will work correctly. But if you want your code to be really clear and readable, you might want to explicitly specify your desired conversion from float to int, such as using:
int tmpInt = floorf(myFloat); // or roundf(), etc.
and then separately specifying how you want the integer formated, e.g.
... stringWithFormat:#"%d", tmpInt ... // or #"%+03d", etc.
instead of assuming that an inline cast shows what you want.
You may also use
double newDvalue =floor(dValue);
it will remove all the decimals point
using %.0f for string format will be good also