Type Int8 in Swift does not store the maximum integer 255

7

Doing some play on the Playground, With Swift 2.2 we can declare constant

let testeIntOitoBits: Int8 = 127 //maximo - deveria ser 255
let testeIntOitoBits2: UInt8 = 255

Why can not I store 255 in type Int8 and in type UInt8 yes?

    
asked by anonymous 18.06.2016 / 01:36

1 answer

8

You can use this to find out the maximum value of a type:

print(Int8.max) //vai responder 127
print(UInt8.max) //vai responder 255

Int8 is an integer type signaled, that is, it has 8 bits and one of them is the signal if the number is positive or negative. Only 7 bits remain to represent the number itself. With 7 bits we can only represent 128 different numbers, so it can only go from 0 to 127. In the case of negatives as it does not have to represent 0, it goes from -1 to -128. Totaling 256 different numbers (-128 to 127). If you get the Int8.min you will get a -128.

Since UInt8 is an unsigned integer ( U means unsigned ) and can use the 8 bits to represent the number, so it can represent 0 to 255. Obviously no may represent negative numbers.

Avoid using unlabeled types. Use only where you really need it and when you understand all of its implications. I reinforce this recommendation: it is rare to be useful to use an unsigned type. You will think you need it, but it will probably be a wrong decision. When you're sure you need to make sure you've understood all the differences of working with arithmetic on a type like that.

    
18.06.2016 / 01:50