I am very new to programming and Python 开发者_StackOverflowso please bear with me. I have a string that is Base64 and I want to convert it to decimal. The string can come in to the script as any value, for example zAvIAQ. This value represents an IP address which is 204.11.200.1 when converted to decimal. What I want to do is convert the Base64 string to decimal and assign it to a variable so that I can use it elsewhere in the script.
I have tried to use the base64.decode function, but that just gives me a very strange text output. I have tried to use the Decimal() function but that gives me an error. After searching for several days now I haven't found a way to do this, at least not one that I can understand. Any help that you can provide would be appreciated.
First decode the base64-encoded string using decode('base64')
and then decode the resulting number into an IP quartet by using socket.inet_ntoa
. Like this:
>>> socket.inet_ntoa('zAvIAQ=='.decode('base64'))
'204.11.200.1'
>>> address=[ord(c) for c in base64.b64decode('zAvIAQ==')]
>>> address
[204, 11, 200, 1]
I usually use base64.b64decode()
. With that you get:
In [18]: base64.b64decode('zAvIAQ==')
Out[18]: '\xcc\x0b\xc8\x01'
That is probably the weird output you were referring to. The point is that you get a byte string back, with each byte representing a value between 0 and 255. Those values might not be printable, hence the \x representation.
But as you know that these are the buckets of an IPv4 address, you go through them converting them to decimals, e.g. with the generator expression:
[ord(c) for c in ...]
and you get the more familiar representation 204, 11, 200, 1.
精彩评论