How to convert HexString into ByteArray in Swift 3

I am trying to convert hexString to byte array ([UInt8]) I searched everywhere but couldn’t find a solution. Below is my quick 2 code

func stringToBytes(_ string: String) -> [UInt8]? {
let chars = Array(string)
let length = chars.count
if length & 1 != 0 {
return nil
}
var bytes = [UInt8]()
bytes.reserveCapacity(length/2)
for var i = 0; i if let a = find(hexChars, chars[i]),
let b = find(hexChars, chars[i+1]) {
bytes.append(UInt8(a << 4) + UInt8(b))
} else {
return nil
}
}
return bytes
}

Example Hex

Hexadecimal: “7661706f72”

expectedOutput: “steam”

This code can generate the same output as the swift 2 code.

func stringToBytes(_ string: String) -> [UInt8]? {
let length = string.characters.count
if length & 1 != 0 {
return nil
}
var bytes = [UInt8]()
bytes.reserveCapacity(length/2)
var index = string.startIndex
for _ in 0. . let nextIndex = string.index(index, offsetBy: 2)
if let b = UInt8(string[index.. bytes.append(b)
} else {
return nil
}
index = nextIndex
}
return bytes
}

let bytes = stringToBytes("7661706f72")
print(String(bytes: bytes!, encoding: .utf8)) //->Optional("vapor")

I’m trying to convert hexString to byte array ([UInt8]) I searched everywhere but couldn’t find a solution. Below is my quick 2 code

func stringToBytes(_ string: String) -> [UInt8]? {
let chars = Array(string)
let length = chars.count
if length & 1 != 0 {
return nil
}
var bytes = [UInt8]()
bytes.reserveCapacity(length/2)
for var i = 0; i if let a = find(hexChars, chars[i]),
let b = find(hexChars, chars[i+1]) {
bytes.append(UInt8(a << 4) + UInt8(b))
} else {
return nil
}
}
return bytes
}

Example Hex

Hexadecimal: “7661706f72”

ExpectedOutput: “Steam”

This code can be generated with swift 2 The same output as the code.

func stringToBytes(_ string: String) -> [UInt8]? {
let length = string.characters.count< br /> if length & 1 != 0 {
return nil
}
var bytes = [UInt8]()
bytes.reserveCapacity(length/2)
var index = string.startIndex
for _ in 0.. let nextIndex = string.index(index, offsetBy: 2)
if let b = UInt8(string[ index.. bytes.append(b)
} else {
return nil
}
index = nextIndex
}
return bytes
}

let bytes = stringToBytes("7661706f72")
print(String(bytes: bytes!, encoding: .utf8)) //->Optional("vapor")

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 4158 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.