Swift converting signed array of Int [int8] to unsigned array of Int [UInt8]

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

How to convert signed array of [Int8] to unsigned array of [UInt8].

 let arryData: [Int8] =  [-108, 11, -107, -14, 35, -57, -116, 118, 54, 91, 12, 67, 21, 29, -44, 111] 

I just want to convert this above into array of Unsigned [UInt8]. How to achieve this in swift.? Thanks in advance.

回答1:

If your intention is to convert signed 8-bit integers to unsigned ones with the same bit representation (e.g. -1 -> 255):

let intArray: [Int8] =  [0, 1, 2, 127, -1, -2, -128] let uintArray = intArray.map { UInt8(bitPattern: $0) }  print(uintArray) // [0, 1, 2, 127, 255, 254, 128] 


回答2:

[Int8] -> [UInt8]

You haven't specified how you want to treat negative values; by flipping them to their positive counterpart or by removing them. Below follows both cases.


Transforming negative values to positive ones by flipping sign:

let arrayData: [Int8] =  [-108, 11, -107, -14, 35, -57, -116, 118, 54, 91, 12, 67, 21, 29, -44, 111] let arrayDataUnsigned = arrayData.map { UInt8(abs($0)) }     /* [108, 11, 107, 14, 35, 57, 116, 118, 54, 91,          12, 67, 21, 29, 44, 111] */ 

Or, by removing the negative values:

let arrayDataUnsigned = arrayData.flatMap { $0 < 0 ? nil : UInt8($0) }     /* [11, 35, 118, 54, 91, 12, 67, 21, 29, 111] */ 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!