Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSInteger types

I would like to know what is the differecnce between Integer 16, Integer 32 and Integer 64, and the difference between a signed integer and an unsigned integer(NSInteger and NSUInteger)

like image 644
Skullhouseapps Avatar asked Feb 07 '11 19:02

Skullhouseapps


3 Answers

I'm not sure exactly what types you mean by "Integer 16", "Integer 32", and "Integer 64", but normally, those numbers refer to the size in bits of the integer type.

The difference between a signed and an unsigned integer is the range of values it can represent. For example, a two's-complement signed 16-bit integer can represent numbers between -32,768 and 32,767. An unsigned 16-bit integer can represent values between 0 and 65,535.

For most computers in use today, a signed integer of width n can represent the values [-2n-1,2n-1) and an unsigned integer of width n can represent values [0,2n).

like image 87
Carl Norum Avatar answered Sep 28 '22 02:09

Carl Norum


NSInteger and NSUInteger are Apple's custom integer data types. The first is signed while the latter is unsigned. On 32-bit builds NSInteger is typedef'd as an int while on 64-bit builds it's typedef'd as a long. NSUInteger is typedef'd as an unsigned int for 32-bit and an unsigned long for 64-bit. Signed types cover the range [-2^(n-1), 2^(n-1)] where n is the bit value and unsigned types cover the range [0, 2^n].

When coding for a single, self-contained program, using NSInteger or NSUInteger are considered the best practice for future-proofing against platform bit changes. It is not the best practice when dealing with fixed-size data needs, such as with binary file formats or networking, because the required field widths are defined previously and constant regardless of the platform bit level. This is where the fixed-size types defined in stdint.h (i.e., uint8_t, uint16_t, uint32_t, etc) come into use.

like image 31
Ryan Avatar answered Sep 28 '22 00:09

Ryan


Unsigned vs signed integer -

Unsigned is usually used where variables aren't allowed to take negative numbers. For example, while looping through an array, its always useful/readable if the array subscript variable is unsigned int and loop through until the length of the array.

On the other hand, if variable can have negative numbers too then declare the variable as signed int. Integer variables are signed by default.

like image 33
Mahesh Avatar answered Sep 28 '22 02:09

Mahesh