///Base64编码
static func encodeBase64(_ s:String) -> String {
return (s.data(using: .utf8)!.base64EncodedString())
}
///Base64解码
static func decodeBase64(_ s:String) -> String {
return String(data: Data(base64Encoded: s)!, encoding: .utf8)!
}
///Base64转Float数组
static func string2Floats(_ s:String) -> [Float] {
//String转[UInt8]
let bs = [UInt8](Data(base64Encoded: s)!)
//[UInt8]转[Float]
return Bytes2Floats(bs)
}
///Float数组转Base64
static func floats2String(_ fs:[Float]) -> String {
//[Float]转[UInt8]
let bs = Floats2Bytes(fs)
//[UInt8]转String
return Data(bytes: bs).base64EncodedString()
}
///Byte数组转Float数组
static func Bytes2Floats(_ bs:[UInt8]) -> [Float] {
var fs = [Float]()
for i in 0 ..< bs.count/4 {
let arr = Array(bs[4*i ..< 4*i+4])
var f:Float = 0
memcpy(&f, arr, 4)
fs.append(f)
}
return fs
}
///Float数组转Byte数组
static func Floats2Bytes(_ fs: [Float]) -> [UInt8] {
var bs = [UInt8]()
for var f in fs {
bs += withUnsafePointer(to: &f) {
$0.withMemoryRebound(to: UInt8.self, capacity: 4) {
Array(UnsafeBufferPointer(start: $0, count: 4))
}
}
}
return bs
}
///四位Byte转Float
static func Bytes2Float(_ bs:[UInt8]) -> Float {
var f:Float = 0.0
memcpy(&f, bs, 4)
return f
}
///Float转四位Byte
static func Float2Bytes(_ value: Float) -> [UInt8] {
var value = value
let size = MemoryLayout<Float>.size
return withUnsafePointer(to: &value) {
$0.withMemoryRebound(to: UInt8.self, capacity: size) {
Array(UnsafeBufferPointer(start: $0, count: size))
}
}
}
主要参考自StackOverflow
网友评论