10

What are the differences between the data types Int & UInt8 in Swift?

Looks like UInt8 is used for binary data, I need to convert UInt8 to Int. Is this possible?

HangarRash
  • 7,314
  • 5
  • 5
  • 32
nuteron
  • 531
  • 2
  • 8
  • 26

4 Answers4

9

That U in UInt stands for unsigned int.

It is not just using for binary data. Uint is used for positive numbers only, like natural numbers. I recommend you to get to know how negative numbers are understood from a computer.

ebug38
  • 171
  • 1
  • 14
5

Int8 is an Integer type which can store positive and negative values.

UInt8 is an unsigned integer which can store only positive values.

You can easily convert UInt8 to Int8 but if you want to convert Int8 to UInt8 then make sure value should be positive.

Piyush
  • 1,156
  • 12
  • 20
3

UInt8 is an 8bit store, while Int not hardly defined or defined by the compiler:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

Int could be 32 or 64 bits

2

Updated for swift:

Operation                 Output Range                        Bytes per Element

uint8                     0 to 255                                   1 

Int          - 9223372036854775808 to 9223372036854775807          2 or 4 

If you want to find the max and min range of Int or UInt8:

 let maxIntValue = Int.max
 let maxUInt8Value = UInt8.max

 let minIntValue = Int.min
 let minUInt8Value = UInt8.min

If you want to convert UInt8 to Int, used below simple code:

func convertToInt(unsigned: UInt) -> Int {
    let signed = (unsigned <= UInt(Int.max)) ?
        Int(unsigned) :
        Int(unsigned - UInt(Int.max) - 1) + Int.min

    return signed
}
Kiran Jadhav
  • 3,209
  • 26
  • 29
  • Newbie here. Thanks, Kiran, I needed that. However, the entire range of UInt8 fits in an Int. Why can't/doesn't the compiler implicitly perform (and allow) the above convertToInt as "let myInt: Int = 1 as UInt8"? – vonlost Aug 04 '20 at 17:53