swift zlib 解压缩

2023-06-11  本文已影响0人  ksnowlv

swift使用zlib框架compress/uncompress进行解压缩,示例代码如下,

    func testDataCompression()  {
        let helloworld = "Hello"
        let data = helloworld.data(using: .utf8)

        // 压缩数据
        var uncompressedSize = uLong(data?.count ?? 0)
        var compressedSize = compressBound(uLong(data!.count))
        var compressedData = Data(count: Int(compressedSize))
        compressedData.withUnsafeMutableBytes { compressedBytes in
            data!.withUnsafeBytes { uncompressedBytes in
                compress(compressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), &compressedSize, uncompressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), uncompressedSize)
            }
        }
        compressedData.count = Int(compressedSize)
        print("压缩后的数据:\(compressedData)")
        
        var uncompressedData = Data(count: Int(uncompressedSize))
        let actualSize = uncompressedData.withUnsafeMutableBytes { uncompressedBytes in
            compressedData.withUnsafeBytes { compressedBytes in
                return uncompress(uncompressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), &uncompressedSize, compressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), uLong(compressedData.count))
            }
        }
        if actualSize != Z_OK {
            print("解压缩数据失败")
        } else {
            let uncompressedString = String(data: uncompressedData, encoding: .utf8)!
            print("解压缩后的数据:\(uncompressedString)")
        }
    }
上一篇下一篇

猜你喜欢

热点阅读