在Swift 4中使用字节

有时需要实现一种算法,用于对Swift项目中的字符串,文件或其他数据进行加密/解密。 不幸的是,这种类型的算法从其他语言(例如Java)到Swift的转换并不简单。

Unicode标量

在幕后,Swift的本机String类型是根据Unicode标量值构建的。 Unicode标量是字符或修饰符的唯一21位数字,例如用于U+1F425 LATIN SMALL LETTER A"a" )的U+0061或用于前"🐥""🐥" )的U+1F425

在Swift中,可以从UnicodeScalar值构造一个UnicodeScalar 。 我们可以从Int构造一个UnicodeScalar 。 这允许许多转换。

使用utf8utf16这两个属性都可以访问String所有Int值。 使用这些属性,我们可以将基于数字的转换应用于字符。

注意:

String转换为byte arrayshort array

 让字符串:字符串=“ abcd” let byteArray:[UInt8] = string.utf8.map {UInt8($ 0)} let shortArray:[UInt16] = string.utf16.map {UInt16($ 0)} //还有另一个带有更多编码的方法如果让数据:Data = string.data(使用:.windowsCP1252,allowLossyConversion:true){//现在,您可以简单地循环遍历datafor i中的字节,即0。.<data.count {data [i] / / UInt8 value} //或者,如果您仍需要UInt8 arraylet byteArrayFromData:[UInt8] = [UInt8](data)} 
//阅读有关数据的更多信息(使用编码:UInt,allowLossyConversion有损:布尔)->数据? 来自Apple文档:
https://developer.apple.com/documentation/foundation/nsstring/1413692-data

byte arrayshort array转换为String

 让byteArray:[UInt8] = [97,98,99,100] let stringFromByteArray =字符串(数据:数据(字节:byteArray),编码:.utf8)let shortArray:[UInt16] = [97,98,99,100 ] let stringFromShortArray = shortArray.reduce(“”,{$ 0 + String(UnicodeScalar($ 1)!)}) 

Character转换为byteshort

 让字符:字符=“ a” let字节:UInt8 =字符串(字符).utf8.map {UInt8($ 0)} [0]简写:UInt16 =字符串(字符).utf16.map {UInt16($ 0)} [ 0] 

byteshort转换为Character

 让字节:UInt8 = 100let characterFromByte:字符=字符(UnicodeScalar(byte))简写:UInt16 = 100 // UnicodeScalar的UInt16参数值是可选的 
让characterFromShort:字符=字符(UnicodeScalar(short)!)

这是一个Character类扩展,用于简化byteshort转换

要检查所有可用的操作员,请从下面提供的链接访问Apple的文档。

  • UInt8 -https://developer.apple.com/documentation/swift/uint8
  • UInt16 -https://developer.apple.com/documentation/swift/uint16

在开始将算法转换为Swift之前,您需要了解一件事,Swift使用Unsigned Integers。

未签名和已签名整数

Swift的UInt8UInt8数据类型是8位无符号整数。 最小值为0 ,最大值为255 (包括255

Java的字节byte数据类型是8位带符号的二进制补码整数。 最小值为-128 ,最大值为127 (含)

Java的short和Swift的UInt16之间的UInt8与上面的byteUInt8相似,因此我们可以使用下一个定义作为参考。

Java被用作示例编程语言来指出差异。 还有其他语言将带符号整数用于byteshort

有关无符号和有符号整数的更多信息,请参见:http://kias.dyndns.org/comath/13.html