faqts : Computers : Programming : Languages : Python : Snippets : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 3 people (33%) answered Yes
Recently 0 of 2 people (0%) answered Yes

Entry

Is there a way to read and write base-n strings using pack or unpack?

Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 37, Guido van Rossum


"""
Packages: maths.bases;basic_datatypes.strings
"""

"""
> Is there a way to read and write base-n strings using pack or unpack.  i.e.
> if I have a string '1001001011' and I tell it to read a 10-digit binary
> string, it would return 587.  If not using pack or unpack, is there another
> way to do it?

Easy:
"""

def getnum(s, base=2):
    x = 0
    for c in s:
            i = ord(c) - ord('0')
            assert 0 <= i < base
            x = x*base + i
    return x
	
print getnum('1001001011')
# 587