Hexadecimal String to Byte Array Conversion

151 Views Asked by At

How to convert 0x01 into byte array in swift.

I need to convert "0x01" into byte array and then the resulting byte array need to share as NSData type

1

There are 1 best solutions below

0
Alirza Eram On
let hexString = "0x01"

// Convert the hex string to an integer value
guard let intValue = Int(hexString, radix: 16) else {
    fatalError("Invalid hex string")
}

// Convert the integer value to a UInt8 value
let byteValue: UInt8 = UInt8(intValue)

// Create a byte array from the UInt8 value
let byteArray = [byteValue]

// Convert the byte array to an NSData object
let data = NSData(bytes: byteArray, length: byteArray.count)