【发布时间】:2022-01-21 21:19:06
【问题描述】:
我在 Python 中有用于压缩和解压缩字符串(字节数组)的函数:
def compress_message(data):
compressor = zlib.compressobj(-1, zlib.DEFLATED, 31, 8, zlib.Z_DEFAULT_STRATEGY)
compressed_data = compressor.compress(data)
compressed_data += compressor.flush()
return compressed_data
def decompress_message(compressed_data):
return zlib.decompress(compressed_data, wbits=31)
我需要将这些函数转换为 kotlin,以便在我的移动应用程序中使用它们。到目前为止,我试过这个:
fun String.zlibCompress(): ByteArray {
val input = this.toByteArray(charset("UTF-8"))
val output = ByteArray(input.size * 4)
val compressor = Deflater().apply {
setLevel(-1)
setInput(input)
finish()
}
val compressedDataLength: Int = compressor.deflate(output)
return output.copyOfRange(0, compressedDataLength)
}
但是,它给出了完全不同的结果,例如字符串abcdefghijklmnouprstuvwxyz:
Python: 1f8b080000000000000a4b4c4a4e494d4bcfc8cccacec9cdcb2f2d282a2e292d2bafa8ac0200c197b2d21a000000
Kotlin: 789c4b4c4a4e494d4bcfc8cccacec9cdcb2f2d282a2e292d2bafa8ac020090b30b24
有什么办法,如何修改 kotlin 代码,使其得到与 Python 相同的结果?
感谢您的回复。
【问题讨论】:
-
请注意这不是代码编写或辅导服务。我们可以帮助解决具体的技术问题,而不是对代码或建议的开放式请求。请编辑您的问题以显示您迄今为止尝试过的内容,以及您需要帮助的具体问题。有关如何最好地帮助我们帮助您的详细信息,请参阅How To Ask a Good Question 页面。另外,由于这不是python问题,所以python标签不正确,请编辑。