Is there an easy way to do this:

I want to take a string and convert it to a binary string with base of my choice and convert it back. So base 2 would be 1's and 0's, etc.


in_string = "testing"

binary_string = string2binary(in_string, base = 2) """ 01110100 01100101 01110011 01110100 01101001 01101110 01100111""" 

out_string = binary2string(binary_string, base = 2)

print out_string ##testing
9 Years
Discussion Span
Last Post by vidaj

To do this you have to know how to convert a number from one base to another. If you take a look at http://www.cut-the-knot.org/recurrence/conversion.shtml, it has a decent explanation.

You can iterate over a string like a list, so you can extract each character. Then you can convert that character to a number using the builtin ord function.

I've translated the java-method given in the above link to python, and made another function that converts string into base-N strings.

import math
def baseConv(m, radix):
    if m < radix:
        return "{0}".format(m)
        return "{0}{1}".format(baseConv(math.floor(m / radix), radix), math.floor(m % radix))

def convString(s, radix):
    return " ".join([baseConv(ord(character), radix) for character in s])

If this is an assignment at school, you really have to read and understand the convertion from one base to another. Try to dissect these methods and find out what they do, and why they do it.

The functions above only work for bases 1-10. I'll leave it up to you to find out why and how to fix it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.