Re: Convert integer to fixed length binary string

Discussion in 'Python' started by Ulrich Eckhardt, Jun 11, 2009.

  1. casebash wrote:
    > I know the bin function converts an int into a binary string.


    Binary string sounds ambiguous. Firstly, everything is binary. Secondly,
    strings are byte strings or Unicode strings. In any case, I'm not 100% sure
    what you mean - giving an example of input and output would help!

    > Unfortunately, I need to know the length of the binary string when it
    > is being read in and len(bin(x)) depends on x. Is there any way to
    > limit it to 4 bytes?


    If you need a piece of four bytes which contain a number in a packed format
    similar to the one used in memory, using bin(x) is the wrong way. Instead,
    take a look at the struct module:

    import struct
    struct.pack('=L', 255)

    Alternatively, also the array module might help.

    Uli

    --
    Sator Laser GmbH
    Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
     
    Ulrich Eckhardt, Jun 11, 2009
    #1
    1. Advertising

  2. Ulrich Eckhardt

    casebash Guest

    Thanks, this is what I needed

    On Jun 11, 9:40 pm, Ulrich Eckhardt <> wrote:
    > casebash wrote:
    > > I know the bin function converts an int into a binary string.

    >
    > Binary string sounds ambiguous. Firstly, everything is binary. Secondly,
    > strings are byte strings or Unicode strings. In any case, I'm not 100% sure
    > what you mean - giving an example of input and output would help!
    >
    > > Unfortunately, I need to know the length of the binary string when it
    > > is being read in and len(bin(x)) depends on x. Is there any way to
    > > limit it to 4 bytes?

    >
    > If you need a piece of four bytes which contain a number in a packed format
    > similar to the one used in memory, using bin(x) is the wrong way. Instead,
    > take a look at the struct module:
    >
    >   import struct
    >   struct.pack('=L', 255)
    >
    > Alternatively, also the array module might help.
    >
    > Uli
    >
    > --
    > Sator Laser GmbH
    > Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
     
    casebash, Jun 12, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sam
    Replies:
    3
    Views:
    14,110
    Karl Seguin
    Feb 17, 2005
  2. Aquila Deus
    Replies:
    3
    Views:
    2,070
    Aquila Deus
    Jul 24, 2004
  3. Mark Dickinson
    Replies:
    0
    Views:
    545
    Mark Dickinson
    Jun 11, 2009
  4. Victor Bazarov
    Replies:
    2
    Views:
    707
    Alf P. Steinbach
    May 3, 2010
  5. cpp4ever
    Replies:
    2
    Views:
    893
    cpp4ever
    May 4, 2010
Loading...

Share This Page