如何在Swift 3中将HexString转换为ByteArray [英] How do i convert HexString To ByteArray in Swift 3

查看:457
本文介绍了如何在Swift 3中将HexString转换为ByteArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将hexString转换为字节数组([UInt8]),我到处搜索但找不到解决方案。下面是我的快捷代码2

I'm was trying to convert hexString to Array of Bytes([UInt8]) I searched everywhere but couldn't find a solution. Below is my swift 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 < length; i += 2 {
        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
} 

十六进制示例

Hex: 7661706f72

Hex : "7661706f72"

expectedOutput: vapor

expectedOutput : "vapor"

推荐答案

此代码可以生成与您的 swift 2代码相同的输出。

This code can generate the same output as your 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..<length/2 {
        let nextIndex = string.index(index, offsetBy: 2)
        if let b = UInt8(string[index..<nextIndex], radix: 16) {
            bytes.append(b)
        } else {
            return nil
        }
        index = nextIndex
    }
    return bytes
}

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

这篇关于如何在Swift 3中将HexString转换为ByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆