bin2chr("01110011") # = 15 function ?

Discussion in 'Python' started by gcmartijn@gmail.com, Feb 25, 2008.

  1. Guest

    H!

    I'm searching for a simple
    bin2chr("01110011") function that can convert all my 8bit data to a
    chr so I can use something like this:

    def bin(i):
    l = ['0000', '0001', '0010', '0011', '0100', '0101', '0110',
    '0111',
    '1000', '1001', '1010', '1011', '1100', '1101', '1110',
    '1111']
    s = ''.join(map(lambda x, l=l: l[int(x, 16)], hex(i)[2:]))
    if s[0] == '1' and i > 0:
    s = '0000' + s
    return s

    print ord("s") # = 115
    print bin(ord("s")) # = 01110011

    test= open('output.ext,'wb')
    test.write(bin2chr("01110011"))
    test.write(bin2chr("01111011"))
    test.write(bin2chr("01110111"))
    test.close()

    I think this is very easy but I'm not very good in python.
    In a other program I use I do something like this

    Function bin2int(b$)
    blen=Len(b)
    For f=1 To blen
    n=n Shl 1 + (Mid(b,f,1)="1")
    Next
    Return n
    End Function
    , Feb 25, 2008
    #1
    1. Advertising

  2. Tim Chase Guest

    > I'm searching for a simple
    > bin2chr("01110011") function that can convert all my 8bit data to a
    > chr so I can use something like this:


    > print ord("s") # = 115
    > print bin(ord("s")) # = 01110011
    >
    > test= open('output.ext,'wb')
    > test.write(bin2chr("01110011"))
    > test.write(bin2chr("01111011"))
    > test.write(bin2chr("01110111"))
    > test.close()


    I think this simple one-liner should do it for you:

    >>> bin2char = lambda s: chr(int(s,2))
    >>> bin2char('01110011')

    's'

    which exploits int()'s ability to take a base (2, in this case).

    -tkc
    Tim Chase, Feb 25, 2008
    #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. James Vanns
    Replies:
    7
    Views:
    7,011
    Evan Carew
    Jan 21, 2004
  2. komal
    Replies:
    6
    Views:
    1,405
    msalters
    Jan 25, 2005
  3. Replies:
    2
    Views:
    894
    Bengt Richter
    Aug 1, 2005
  4. Giannis Papadopoulos

    Function pointer to void function and int function

    Giannis Papadopoulos, Sep 5, 2005, in forum: C Programming
    Replies:
    5
    Views:
    1,216
    Barry Schwarz
    Sep 5, 2005
  5. weafon
    Replies:
    1
    Views:
    288
    Diez B. Roggisch
    Jul 14, 2009
Loading...

Share This Page