///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轉(zhuǎn)Float數(shù)組
static func string2Floats(_ s:String) -> [Float] {
//String轉(zhuǎn)[UInt8]
let bs = [UInt8](Data(base64Encoded: s)!)
//[UInt8]轉(zhuǎn)[Float]
return Bytes2Floats(bs)
}
///Float數(shù)組轉(zhuǎn)Base64
static func floats2String(_ fs:[Float]) -> String {
//[Float]轉(zhuǎn)[UInt8]
let bs = Floats2Bytes(fs)
//[UInt8]轉(zhuǎn)String
return Data(bytes: bs).base64EncodedString()
}
///Byte數(shù)組轉(zhuǎn)Float數(shù)組
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數(shù)組轉(zhuǎn)Byte數(shù)組
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轉(zhuǎn)Float
static func Bytes2Float(_ bs:[UInt8]) -> Float {
var f:Float = 0.0
memcpy(&f, bs, 4)
return f
}
///Float轉(zhuǎn)四位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