I have a list containing negative numbers, and want to encode the list with base64. How can I do that?
I tried:
l = [-10, -48, 100, -20]
bytes(l)
But I get the error:
ValueError: bytes must be in range(0, 256)
I expect the same output as my Java code:
byte[] bytes = {-10, -48, 100, -20};
String result = Base64Utils.encodeToUrlSafeString(bytes);
System.out.println(result); // 9tBk7A==
The error arises because Python expects unsigned 8-bit data, which can be obtained with the modulo %
operation 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=='
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.