I am making a binary to decimal number converter on iphone. having some problem when i trying to take each single digit from a number and do calculation. I tried char, characterAtIndex but they all failed to do calculation or i got the syntax completely wrong. Can anyone show me how to do such cast or there is an easier approach?
Your problem is getting numbers from strings?
The easiest way to get an integer from a character is to use the ascii table, like this:
NSString *stringOfNums = #"15";
char c;
int num;
for (int i = 0; i < [stringOfNums length]; ++i) {
c = [stringOfNums characterAtIndex:i];
num = c - 48; // 0 is 48 in ascii table
printf("\nchar is %c and num is %d", c, num);
}
The advantage of this method is that you can validate on a char-by-char basis that each falls in a range of 48 through 57, the ascii digits.
Or you could do the conversion in one step using NSNumberFormatter, as described here: How to convert an NSString into an NSNumber
As for the binary-decimal conversion, does your formula work on paper? Get that right first.
Related
In C++, there is a std::setprecision function can set float/double precision.
how can i set precision in Objective-C? and this print below:
(lldb) p 10/200
(int) $0 = 0
(lldb) p (float)10/200
(float) $1 = 0.0500000007
line 3 result is 0.0500000007, why is '7' in the result? how can i get the result is 0.05?
Floating-point numbers are binary floating-point numbers. 0.05 cannot be represented exactly by a binary floating point number. The result cannot ever be exactly 0.05.
In addition, you are quite pointlessly using float instead of double. float has only six or seven digits precision. Unless you have a very good reason that you can explain, use double, which gives you about 15 digits of precision. You still won't be able to get 0.05 exactly, but the error will be much less.
You may use NSNumberFormatter to format objects in a wide variety of ways --- too numerous to list here, see the documentation available from Xcode. Also see the Data Formatting Guide.
You must make change between % modulo operator and its identifier f in order to get desired result.
NSString* formattedNumber = [NSString stringWithFormat:#"%.02f", myFloat];
%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.
Example:
%f = 25.000000 // results 25.000000
%.f = 25 // results 25
%.02f = 25.00 // results 25.00
plz use
double A = 0.0500000007;
NSString *b =[NSString stringWithFormat:#"$%.02f",A] ;
double B = [b doubleValue];
So I ran into a huge issue at work because I had something like this in my code:
int foo = -1;
NSArray *bar = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
if (foo > [bar count]){
NSLog(#"Wow, that's messed up.");
} else {
NSLog(#"Rock on!");
}
As you probably already know by me posting this, the output is:
"Wow, that's messed up."
From what I gather, objective C is converting my negative number to a "signed" int and thus, killing my compare.
I saw other posts about this and they all stated what the problem was but none of them suggested any simple solutions to get this comparison to actually work. Also, I'm shocked that there are no compiler warnings, as these are causing serious issues for me.
The problem
The problem you're experiencing is that because foo is a signed integer and -[NSArray count] returns an unsigned integer, foo is undergoing implicit type conversion to unsigned integer. See Implicit Type Conversion for more information. Also, there's more information about type conversion rules in C here.
The solution
-[NSArray count] returns an unsigned value because an array can never have a negative number of elements; the smallest possible value is 0. Comparing an array's count to -1 doesn't make a lot of sense -- the count will always be larger than any negative number (sign problems notwithstanding).
So, the right solution here, and the way to avoid these kinds of problems, is to use a type that matches the return value of -[NSArray count], namely NSUInteger (the U is for unsigned).
Try this
- (IBAction)btnDoSomething:(id)sender {
int foo = -1;
NSArray *bar = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
if ( foo > (signed)[bar count] ) {
NSLog(#"Wow, that's messed up.");
} else {
NSLog(#"Rock on!");
}
}
Working
If you are comparing two different type of variables then it will implicitly convert data type of both variables to higher type of them.
In this example,
variable foo is of type signed int and array count is of unsigned int,
So it will convert data type of foo to unsigned int
then value of foo will become large number, which is smaller than array count 3.
So in this example you need to down cast array count to signed int.
Issues
When your array count exceeds max limit of signed int then after casting it will rounded back like [ -(negative) max limit -> 0 -> + max limit ] which is unexpected result.
Solution
Avoid type casting if you are not sure about maximum array length.
Do casting if you are sure for limit(maximum array length will not exceeds signed int max limit).
For more details check this
http://visualcplus.blogspot.in/2006/02/lesson-4-casting-data-types.html
Simple question, I know there must be a correct way to do this. I have a CGFloat that increases in increments of 1/16. I want to determine when this value becomes a whole number.
For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations and mod 16 it.
While you generally can't count on fractional floating point numbers to sum up to whole numbers, your case is exception to the rule since 1/16 is 2^(-4) and this number can be represented by float precisely:
- (void)testFloat
{
float a = 0.0f;
while (a != 2.0f) {
a += 0.0625f;
}
NSLog(#"OK!");
}
It's better to do it the other way around, i.e. use an integer loop counter and convert this to a float:
for (int i = 0; i < 100; ++i)
{
float x = (float)i / 16.0f;
if (i % 16 == 0)
{
// if x is whole number...
}
}
Floating point arithmetic is inexact so you can't count on the value of your variable ever being exactly 2.0000.
"For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations andmod 16 it."
This is a wonderful idea.
objective c math function question
I've got a x value that i'd like to compare to other values within a set, then determine which value from the set my x value is closest to.
For example, lets say i've got the ints 5, 10, 15, 20, 25.
What is the best way to determine which of these numbers is closest to 7?
int closestDistance = INT32_MAX;
int indexOfClosestDistance = -1;
int x = 7;
for (int i=0; i < [yourArray count]; i++)
{
int num = yourArray[i];
int diff = abs(num - x);
if (diff < closestDistance)
{
closestDistance = diff;
indexOfClosestDistance = i ;
}
}
Best of luck
Neither Objective-C nor Cocoa provides anything that solves this for you. You can store your ints in a plain old array of int, or you can wrap each one in an NSNumber and store the wrappers in an NSArray.
If you're going to probe the array many times, sort it once in advance, and then for each probe use a binary search (standard C function bsearch or Core Foundation's CFArrayBSearchValues or Cocoa's -[NSArray indexOfObject:inSortedRange:options:usingComparator:]) to find the nearest two elements. If you're only going to probe the array once or twice, just use a for loop, subtraction, abs, and MIN.
The easiest way is subtract the smaller number from the larger one. So you'd want to compare the two numbers first, then just do simple subtraction. So you'd see the 10-7 is 3 away, and 7-5 is only 2 away.
So what I want, is for example to convert the letter 'a' into 97 (such as it is in the ASCII table), and then convert 67 into 'a'.
I actually perform a load of mathematics and stuff to the letter, treating it as binary number - so the transition is necessary.
However for special characters it is not working nicely.
char c = 'ÿ';
int i = int(c);
wchar_t wTemp = static_cast<wchar_t>(i);
wchar_t* w = &wTemp;
String^ newI = gcnew String(w);
That symbol is just a random one I found in an image (the type of character that will need to be read). It just comes out as a completely different symbol. I have no idea why, or what to do?
Characters above 0x7f (127) are probably converting to negative integer values. Maybe change c to unsigned:
unsigned char c = 'ÿ';
int i = c;
Your code doesn't look quite right to me though I didn't run it. Here is a good example from MSDN how to convert from and to wchar_t:
http://msdn.microsoft.com/en-us/library/ms235631(v=vs.80).aspx
I don't believe there is anything special about 'special' characters.