Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift convert HexString to Integer

Tags:

arrays

swift

byte

I have a data source in String example

HexString = "72AE"

and i would like to convert it into byte and store into byte array

bytearray = [72, AE]  //UInt8

i know i can do this by

let hexaString = "72AE"
let resultArray = hexaString.characters.map{Int(strtoul(( String($0)), nil, 16))}

print(resultArray)  // "[7, 2, 10, 14]"

but it is not returning the value i want. I have also tried to chop it into hexaString1 = "72" hexaString2 = "AE" but still i can't manage to get the correct value.

like image 719
wes. i Avatar asked Jun 29 '26 12:06

wes. i


1 Answers

Hope this will help you

let hexaString = "72AE"
var byteArray = [UInt8]()
byteArray += hexaString.utf8  // Convert into byte array

// Retain the orginal string from byte array
let stringFromByteArray = NSString(bytes: byteArray, length: byteArray.count, encoding: NSUTF8StringEncoding)
like image 129
Muzahid Avatar answered Jul 01 '26 03:07

Muzahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!