Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > bin2chr("01110011") # = 15 function ?

Reply
Thread Tools

bin2chr("01110011") # = 15 function ?

 
 
gcmartijn@gmail.com
Guest
Posts: n/a
 
      02-25-2008
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
 
Reply With Quote
 
 
 
 
Tim Chase
Guest
Posts: n/a
 
      02-25-2008
> 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



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Function versus pointer to function, in context of std::function,huh? Alf P. Steinbach C++ 10 07-27-2011 05:51 AM
Function pointer to void function and int function Giannis Papadopoulos C Programming 5 09-05-2005 09:06 PM
How override ALL function calls? (Is there a "function call function"?) seberino@spawar.navy.mil Python 2 08-01-2005 12:38 PM
write a function such that when ever i call this function in some other function .it should give me tha data type and value of calling function parameter komal C++ 6 01-25-2005 11:13 AM
Passing a C++ object's member function to a C function expecing a function pointer! James Vanns C++ 7 01-21-2004 02:39 AM



Advertisments