How to convert HEX string to UInt16?

徘徊边缘 提交于 2019-12-08 02:03:52

问题


I have a HEX string d285 and I want to convert it UInt16, please guide me how I can convert it. I tried this

let buffer = UInt16("\(UInt8(text, radix: 16)!)")
return Data(bytes: (buffer?.bigEndian.toBytes)!)

but it's not working


回答1:


UInt16 has an initializer that takes a string and radix value. This can be used to create UInt16 from string.

let hexString = "d285"
let hexToInt = UInt16(hexString, radix: 16) // prints 53893



回答2:


let hexStr = "d285"
var byteArr = [UInt8]()
byteArr += hexStr.utf8  // Convert into byte array

let str = NSString(bytes: byteArr, length: byteArr.count, encoding: String.Encoding.utf8.rawValue)
let number = UInt(str, radix: 16)!

Hope this will help you



来源:https://stackoverflow.com/questions/46644093/how-to-convert-hex-string-to-uint16

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