Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #26662

Re: [newbie] String to binary conversion

Date 2012-08-06 22:56 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: [newbie] String to binary conversion
References <jvpafd$vig$1@news.albasani.net>
Newsgroups comp.lang.python
Message-ID <mailman.3033.1344290169.4697.python-list@python.org> (permalink)

Show all headers | View raw


On 06/08/2012 21:46, Mok-Kong Shen wrote:
>
> 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.
>
Try this (Python 3, in which strings are Unicode):
>>> import struct
 >>> # For a little-endian integer
>>> struct.unpack("<I", "abcd".encode("latin-1"))[0]
1684234849
>>> hex(_)
'0x64636261'

or this (Python 2, in which strings are bytestrings):
 >>> import struct
 >>> # For a little-endian integer
 >>> struct.unpack("<I", "abcd")[0]
1684234849
 >>> hex(_)
'0x64636261'

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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