Python与Scala的Base64解码结果不一致问题求助
Base64解码:Scala与Python结果不一致问题解决
问题背景
将Scala代码重构为Python3时,遇到Base64字符串解码结果显示不匹配的问题:Python的base64.b64decode输出与Scala的decodeBase64输出在显示形式上存在差异,但底层字节数据完全一致,只需转换为统一的带符号字节数组形式即可匹配。
Scala代码及输出
import org.apache.commons.codec.binary.Base64.decodeBase64 val coded_str = "UgKgDwhoEAAANAEA1tYAADABABoBABMAAAAAAQAAAAEAAQACAAAAAAD6sT4AO0YAAA==" decodeBase64(coded_str) // Output 1 : res1: Array[Byte] = Array(82, 2, -96, 15, 8, 104, 16, 0, 0, 52, 1, 0, -42, -42, 0, 0, 48, 1, 0, 26, 1, 0, 19, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, -6, -79, 62, 0, 59, 70, 0, 0) coded_str.getBytes() // Output 2 res2: Array[Byte] = Array(85, 103, 75, 103, 68, 119, 104, 111, 69, 65, 65, 65, 78, 65, 69, 65, 49, 116, 89, 65, 65, 68, 65, 66, 65, 66, 111, 66, 65, 66, 77, 65, 65, 65, 65, 65, 65, 81, 65, 65, 65, 65, 69, 65, 65, 81, 65, 67, 65, 65, 65, 65, 65, 65, 68, 54, 115, 84, 52, 65, 79, 48, 89, 65, 65, 65, 61, 61)
Python尝试代码及输出
import base64 coded_str = 'UgKgDwhoEAAANAEA1tYAADABABoBABMAAAAAAQAAAAEAAQACAAAAAAD6sT4AO0YAAA==' print(base64.b64decode(coded_str)) # Output 1 : b'R\x02\xa0\x0f\x08h\x10\x00\x004\x01\x00\xd6\xd6\x00\x000\x01\x00\x1a\x01\x00\x13\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x01\x00\x02\x00\x00\x00\x00\x00\xfa\xb1>\x00;F\x00\x00' # Command 2: b = [ord(s) for s in coded_str] print(b) # Output 2 [85, 103, 75, 103, 68, 119, 104, 111, 69, 65, 65, 65, 78, 65, 69, 65, 49, 116, 89, 65, 65, 68, 65, 66, 65, 66, 111, 66, 65, 66, 77, 65, 65, 65, 65, 65, 65, 81, 65, 65, 65, 65, 69, 65, 65, 81, 65, 67, 65, 65, 65, 65, 65, 65, 68, 54, 115, 84, 52, 65, 79, 48, 89, 65, 65, 65, 61, 61]
解决方案
Scala的Byte类型是有符号整数(范围-128到127),而Python的bytes对象中每个元素是无符号整数(范围0到255),二者仅显示形式不同,底层字节数据完全一致。要让Python输出匹配Scala的带符号字节数组,只需将无符号字节转换为有符号:
import base64 coded_str = 'UgKgDwhoEAAANAEA1tYAADABABoBABMAAAAAAQAAAAEAAQACAAAAAAD6sT4AO0YAAA==' decoded_bytes = base64.b64decode(coded_str) # 转换为带符号字节数组 signed_byte_array = [byte if byte < 128 else byte - 256 for byte in decoded_bytes] print(signed_byte_array)
运行上述代码,输出将与Scala的Output 1完全一致:
[82, 2, -96, 15, 8, 104, 16, 0, 0, 52, 1, 0, -42, -42, 0, 0, 48, 1, 0, 26, 1, 0, 19, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, -6, -79, 62, 0, 59, 70, 0, 0]
内容的提问来源于stack exchange,提问作者tde
相关产品推荐
相关产品推荐

