美文网首页
swift zlib 解压缩

swift zlib 解压缩

作者: ksnowlv | 来源:发表于2023-06-11 20:06 被阅读0次

    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)")
            }
        }
    

    相关文章

      网友评论

          本文标题:swift zlib 解压缩

          本文链接:https://www.haomeiwen.com/subject/qskfydtx.html