scarlett scarlett - 1 year ago 120
Python Question

Hex to base-64 and other bases

I have some string representing a number in hex and am asked to convert it to base-64.

The first thing I thought of was (I'm a noob) implementing a simple algorithm that would proceed as one would when working with pen and paper, though I imagine Python has this sort of stuff "built-in".

Through Google I am able to find answers to the above and other similar questions, but I don't want to just "plug and chug", I want to be able to understand what's going on, as I am going to be doing this type of thing a lot and don't want to have to resort to the Internet every time. For instance, what's with strings of the type

and why does
seems to only accept objects of this type as arguments?, why does
only work up to base-36 and how can I in general handle conversion between different bases tidily? So if anyone could give me some pointers here. I am not being able to extract much from the documentation as this type of knowledge seems to be already expected.


Answer Source

Here is a code that walks you trough the process of converting from a hex string to a b64 encoded string.

import base64
print("x  : ",x)
print("b  : ",b)
print("e  : ",e)
print("b2 : ",int(b2.hex(),base=16))


x  :  2882400001
b  :  b'\xab\xcd\xef\x01'
e  :  b'q83vAQ=='
b2 :  2882400001

Some (lengthy) explanations: so we start with a hex in a string, nothing special, int takes it along with the base to turn it into a regular integer x. To python x is a bunch of bits representing a number that will be printed in base 10 most of the time. We can ask the bit representation using x.to_bytes. The result is a sequence of bytes that will print as b'...' note that the printing process automatically tries to convert the bytes to ascii caracters or to somthing like\xab if that given byte isn't associated with a ascii character. So we then feed the bytes to b64encode that is usually use to process files hence that byte-object requirement and it spits an ascii-string as a byte object. With that result the reverse process is similar : b64 ascii-string -> binary number in bytes -> hex -> int.