[英]How to encode list of numbers as base64
我有一個包含負數的列表,並且想用base64編碼該列表。 我怎樣才能做到這一點?
我試過了:
l = [-10, -48, 100, -20]
bytes(l)
但是我得到了錯誤:
ValueError: bytes must be in range(0, 256)
我期望與我的Java代碼具有相同的輸出:
byte[] bytes = {-10, -48, 100, -20};
String result = Base64Utils.encodeToUrlSafeString(bytes);
System.out.println(result); // 9tBk7A==
出現錯誤是因為Python需要無符號的8位數據,可以通過對%
運算取模unsigned == signed % 2 ** num_bits
:
import base64
l = [-10, -48, 100, -20]
# 2 ** 8 == 256
base64.b64encode(bytes(x % 256 for x in l))
# b'9tBk7A=='
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.