How do I convert UInt8 to Data?

How do I convert UInt8 into an object of type Data and still keep it's original value, so that when I convert the Data object back to Uint8, I would get its original value?

Answered by OOPer in 368999022

You should better check the documentation of Data first.


Generally, Data is considered to be a collection of UInt8's, so it naturally keeps the original UInt8 values.

//UInt8 to Data
let value: UInt8 = 123
let data = Data([value])

//Data to UInt8
let originalValue = data[0]
print(originalValue) //->123

//[UInt8] to Data
let arrValue: [UInt8] = [123, 234]
let arrData = Data(arrValue)

//Data to [UInt8]
let originalValues = Array(arrData)
print(originalValues) //->[123,234]


But, in many cases there are some ways you can handle your original values without converting Data to Array of UInt8.

Accepted Answer

You should better check the documentation of Data first.


Generally, Data is considered to be a collection of UInt8's, so it naturally keeps the original UInt8 values.

//UInt8 to Data
let value: UInt8 = 123
let data = Data([value])

//Data to UInt8
let originalValue = data[0]
print(originalValue) //->123

//[UInt8] to Data
let arrValue: [UInt8] = [123, 234]
let arrData = Data(arrValue)

//Data to [UInt8]
let originalValues = Array(arrData)
print(originalValues) //->[123,234]


But, in many cases there are some ways you can handle your original values without converting Data to Array of UInt8.

How do I convert UInt8 to Data?
 
 
Q