Skip to content
Advertisement

How to encode list of numbers as base64

I have a list containing negative numbers, and want to encode the list with base64. How can I do that?

I tried:

JavaScript

But I get the error:

JavaScript

I expect the same output as my Java code:

JavaScript

Advertisement

Answer

The error arises because Python expects unsigned 8-bit data, which can be obtained with the modulo % operation:

unsigned == signed % 2 ** num_bits

JavaScript

This can also be hard-coded for performance:

JavaScript

To convert this back you need loop through base64.b64decode() and convert the unsigned data back to signed reverting the % with a ternary conditional operator:

signed == unsigned if unsigned < 2 ** (num_bits - 1) else unsigned - 2 ** num_bits

JavaScript

or, hard-coding the function:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement