简体   繁体   中英

Integer Precision and Conversion Errors

I have been programming Objective-C for only a few weeks. My experience in programming languages such as basic, visual basic, C++ and PHP is much more extensive starting back in 1987 and continuing forward to today. Although, for the last 5 years, I have exclusively coded PHP.

Today, I find myself confused by what I perceive to be bit conversion errors within the Objective-C language. I first noticed this the other day when trying to divide an integer (84) converted to a float by a float (10.0). This produced 8.399999, instead of the 8.400 I was hoping for. I coded a way around the issue and moved on.

Today, I am extracting an (int) 0 from an NSMutableDictionary. I store it first in an NSInteger and second in an int variable. The values should be 0 for both cases, but for both cases, I get the integer value 151229568. (See screenshot)

I remember from my early programming years that we had to worry about the size of the container, because pointing to block of memory with a 32-bit pointer to access a 4-bit value resulted in capturing all the data associated with other values and thus resulted in what appeared to be the wrong number being captured. With implicit memory management and type-conversions becoming the norm, I have not had to worry about this kind of issue for years, and now that I am confronted with it again, I need advice and clarification from programmers who are more familiar with this topic in todays programming environments.

Questions:

  1. Is this a case of incorrect pointer sizing or something else?
  2. What is happening on the back-end to produce this conversion from 0 to another number?
  3. What can I do to get better precision and accuracy from my Objective-C calculations and variable assignments?

Code:

NSInteger hsibs = [keyData objectForKey:@"half_sibs"];
int hsibsi = [keyData objectForKey:@"half_sibs"];
//breakpoint and screen capture of variables in stack

显示字典和测试变量的内存值的屏幕截图

I don't know Objective C all that well, but it looks like the method you use to obtain your data is returning a data type of id (see this reference ), and not int

Looks like you either need to cast it or get the integer value in such a manner:

NSInteger hsibs = [[keyData objectForKey:@"half_sibs"] integerValue];
int hsibsi = [[keyData objectForKey:@"half_sibs"] intValue];

and then see if you get the expected results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM