【问题标题】:Difference between Int and Uint8 swiftInt 和 Uint8 swift 的区别
【发布时间】:2017-11-12 21:04:20
【问题描述】:

swift中数据类型Int和UInt8有什么区别。

看起来 UInt8 用于二进制数据,我需要将 UInt8 转换为 Int 是否可能。

【问题讨论】:

    标签: swift int swift-data


    【解决方案1】:

    UInt 中的 U 代表 unsigned int。

    它不仅仅用于二进制数据。 Uint 仅用于正数,如自然数。 我建议您了解如何从计算机上理解负数。

    【讨论】:

      【解决方案2】:

      Int8是Integer类型,可以存储正负值。

      UInt8 是一个无符号整数,只能存储正值。

      您可以轻松地将 UInt8 转换为 Int8,但如果您想将 Int8 转换为 UInt8,请确保值应该是正数。

      【讨论】:

        【解决方案3】:

        UInt8 是一个 8 位存储,而 Int 几乎没有被编译器定义或定义:

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

        Int 可以是 32 位或 64 位

        【讨论】:

          【解决方案4】:

          为 swift 更新:

          Operation                 Output Range                        Bytes per Element
          
          uint8                     0 to 255                                   1 
          
          Int          - 9223372036854775808 to 9223372036854775807          2 or 4 
          

          如果要求 Int 或 UInt8 的最大最小范围:

           let maxIntValue = Int.max
           let maxUInt8Value = UInt8.max
          
           let minIntValue = Int.min
           let minUInt8Value = UInt8.min
          

          如果要将 UInt8 转换为 Int,使用下面的简单代码:

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

          【讨论】:

          • 这里是新手。谢谢,基兰,我需要那个。但是,UInt8 的整个范围都适合 Int。为什么编译器不能/不隐式执行(并允许)上述 convertToInt 为“let myInt: Int = 1 as UInt8”?
          猜你喜欢
          • 1970-01-01
          • 2015-02-10
          • 2010-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多