0

I am currently beginning python, and writing a program that will convert a given long string of hex numbers, that should be separated into pairs. I am having a hard time utilizing pythons encoding function.

So far, I have:

import base64

def splitByTwo(str):
    return [i+j for i,j in zip(list(str)[::2], list(str)[1::2])]

def bytesToBase64(str):
    b64List = []
    stringsByTwo = splitByTwo(str.upper())
    for x in stringsByTwo:
        b64List.insert(stringsByTwo.index(x), base64.b16decode(x))
    return b64List

print(bytesToBase64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"))

I can get it to print [b'I', b"'", b'm', b'm', b'm', b' ', b' ',.....] but I am not sure what is wrong with my encode/decode to base64 section of the bytesToBase64() method.

1 Answer 1

2

Your bytesToBase64 function returns a list of bytes represented by the given hex string (garbled a little bit because you used insert instead of append). You haven't done the base64 encoding part.

To fix your existing function:

def bytesToBase64(str):
    b64List = []
    stringsByTwo = splitByTwo(str.upper())
    for x in stringsByTwo:
        b64List.append(base64.b16decode(x))
    print base64.b64encode("".join(b64List))

But this function is not very idiomatic. To completely rewrite it:

def bytesToBase64(s):
    return base64.b64encode(binascii.unhexlify(s))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the solution. I was having a hard time understanding the functionality of the base64 part, as in how it uses and what it uses as arguments. The documentation was a little hard to understand, but now I get it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.