Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #26668
| From | Emile van Sebille <emile@fenx.com> |
|---|---|
| Subject | Re: [newbie] String to binary conversion |
| Date | 2012-08-06 15:45 -0700 |
| References | <jvpafd$vig$1@news.albasani.net> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3038.1344293171.4697.python-list@python.org> (permalink) |
On 8/6/2012 1:46 PM Mok-Kong Shen said...
>
> If I have a string "abcd" then, with 8-bit encoding of each character,
> there is a corresponding 32-bit binary integer. How could I best
> obtain that integer and from that integer backwards again obtain the
> original string? Thanks in advance.
It's easy to write one:
def str2val(str,_val=0):
if len(str)>1: return str2val(str[1:],256*_val+ord(str[0]))
return 256*_val+ord(str[0])
def val2str(val,_str=""):
if val>256: return val2str(int(val/256),_str)+chr(val%256)
return _str+chr(val)
print str2val("abcd")
print val2str(str2val("abcd"))
print val2str(str2val("good"))
print val2str(str2val("longer"))
print val2str(str2val("verymuchlonger"))
Flavor to taste.
Emile
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
[newbie] String to binary conversion Mok-Kong Shen <mok-kong.shen@t-online.de> - 2012-08-06 22:46 +0200
Re: [newbie] String to binary conversion Tobiah <toby@tobiah.org> - 2012-08-06 13:59 -0700
Re: [newbie] String to binary conversion Tobiah <toby@tobiah.org> - 2012-08-06 14:01 -0700
Re: [newbie] String to binary conversion Mok-Kong Shen <mok-kong.shen@t-online.de> - 2012-08-06 23:33 +0200
Re: [newbie] String to binary conversion MRAB <python@mrabarnett.plus.com> - 2012-08-06 22:56 +0100
Re: [newbie] String to binary conversion Emile van Sebille <emile@fenx.com> - 2012-08-06 15:45 -0700
Re: [newbie] String to binary conversion Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-08-07 02:01 +0000
Re: [newbie] String to binary conversion 88888 Dihedral <dihedral88888@googlemail.com> - 2012-08-07 13:17 -0700
csiph-web