【问题标题】:How to convert UInt8 to data type that can be concatenated to a string?如何将 UInt8 转换为可以连接到字符串的数据类型?
【发布时间】:2016-04-01 06:18:33
【问题描述】:

我已经加密了一个在 UInt8 中输出的字符串

[107, 200, 119, 211, 247, 171, 132, 179, 181, 133, 54, 146, 206, 234, 69, 197]

如何将其转换为可以连接到 URL 的数据类型,然后可以使用 PHP 解密?我尝试将其转换为 base64 或十六进制,但是我找不到任何有关如何执行此操作的信息。

【问题讨论】:

    标签: swift encoding type-conversion


    【解决方案1】:

    数据不能直接转换为字符串,因为许多数据字节不能表示为字符串字符。显而易见的选择是编码为 Base64 或十六进制。 Apple 不提供和转换为十六进制,因此最好的选择似乎是 Base64。

    let bytes: [UInt8] = [107, 200, 119, 211, 247, 171, 132, 179, 181, 133, 54, 146, 206, 234, 69, 197]
    
    // Convert to NSData
    let data = NSData(bytes: bytes, length: bytes.count)
    
    // Convert to Base64
    let base64String = data.base64EncodedStringWithOptions([])
    
    print("base64String: \(base64String)")
    

    输出:

    base64String: a8h30/erhLO1hTaSzupFxQ==

    在大多数情况下,Base64 需要进行 URL 编码,因为可能包含“/”和/或“=”字符,具体取决于 URL 字符串的部分。有关 URL 编码信息,请参阅此 SO answer

    【讨论】:

      【解决方案2】:
      let bytes: [UInt8] = [107, 200, 119, 211, 247, 171, 132, 179, 181, 133, 54, 146, 206, 234, 69, 197]
      let base64String = bytes.withUnsafeBufferPointer { buffer -> String in
          let data = NSData(bytes: buffer.baseAddress, length: buffer.count)
          return data.base64EncodedStringWithOptions([])
      }
      print(base64String)
      

      输出:

      a8h30/erhLO1hTaSzupFxQ==
      

      【讨论】:

        猜你喜欢
        • 2013-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        相关资源
        最近更新 更多