我正在嘗試使用實體方法解Codable壓縮在 iPhone 上壓縮的一些 JSON(代表一種型別)。Note是Apple 為便于攜帶而推薦的格式。NSData.compressed(using: .zlib).zlib
zlibPython 3 的庫(在 macOS 12.2 或 Ubuntu Linux 21.10 上)或命令列uncompress(在 macOS 上)等工具無法識別輸出位元組。
問題:如何在其他設備上解壓縮這些資料/不在 Apple 的 Swift 中解壓?
這是一個基本示例,可以按照本指南投入compressor.swift并編譯/運行以生成壓縮資料
import Foundation
struct SomeThing: Codable {
var thing: String
init(thing: String) {
self.thing = thing
}
}
let thing = SomeThing(thing: "abc")
let encoder = JSONEncoder()
let encodedThing = try encoder.encode(thing)
let compressedEncodedThing = try (encodedThing as NSData).compressed(using: .zlib)
try compressedEncodedThing.write(to: URL(fileURLWithPath: "/path/to/somewhere/abc.Z"),
options: [])
在 macOS 上編譯和運行它會產生abc.Z預期的結果。
這段代碼會解壓我們剛剛寫的檔案,只要我們在macOS上編譯:
import Foundation
let readBytes = try! Data(contentsOf: URL(fileURLWithPath: "/path/to/somewhere/abc.Z"))
let decompressed = try! (readBytes as NSData).decompressed(using: .zlib) as Data
let decompString = String(decoding: decompressed, as: UTF8.self)
print(decompString) // prints {"thing": "abc"}
在 Linux 上嘗試同樣的事情(Ubuntu 21.10 和 Swift 5.5.3 Release 工具鏈),
$ swiftc decompressor.swift
decompressor.swift:5:47: error: value of type 'NSData' has no member 'decompressed'
let decompressed = try! (readBytes as NSData).decompressed(using: .zlib) as Data
~~~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~~
decompressor.swift:5:68: error: cannot infer contextual base in reference to member 'zlib'
let decompressed = try! (readBytes as NSData).decompressed(using: .zlib) as Data
這表明開源NSData缺乏蘋果硬體/作業系統上的一些方法。
我嘗試過的其他事情強烈表明沒有使用真正的 ZLib 編碼:
- 打電話
(來自生產的同一臺 macOS 計算機uncompress abc.Zabc.Z)回傳
我也嘗試過使用uncompress: abc.Z: Inappropriate file type or formatgunzip, 來類似的失敗訊息。 - 在 Python 3 中嘗試
zlib.decompress過。Python 失敗可能是提供最多資訊的:此腳本因錯誤而崩潰error: Error -3 while decompressing data: incorrect header checkimport zlib with open("/path/to/somewhere/abc.Z", "rb") as f: bytesRead = f.read() decompressed = zlib.decompress(bytesRead) print(decompressed) - 檔案的前 20 個位元組(十六進制)是:
$ od -x -N 20 abc.Z 0000000 56ab c92a ccc8 574b 52b2 4c4a 564a 05aa 0000020 0000 0000021
uj5u.com熱心網友回復:
您的資料似乎是原始的放氣流。在 python 中,您可以嘗試zlib.decompress(bytesRead, wbits=-15).
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/425588.html
下一篇:從字串資料型別到影像的影像轉換
