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)
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With