PSE Entertainment Corp
February 06, 2012, 02:54:39 PM
Welcome,
Guest
. Please
login
or
register
.
1 Hour
1 Day
1 Week
1 Month
Forever
Login with username, password and session length
News
: Enjoy PSE Tunes! They're great!
Home
Help
Search
Login
Register
PSE Entertainment Corp
>
Development
>
Python
>
Python - Bit and Byte Twiddling
Pages: [
1
]
« previous
next »
Print
Author
Topic: Python - Bit and Byte Twiddling (Read 3508 times)
webmast
Guest
Python - Bit and Byte Twiddling
«
on:
January 30, 2008, 09:34:42 PM »
To Hex an Integer...:
>>> hex(56)
>>> 0x38
To Integer a Hex...:
>>> int('0xED',16)
>>> 237
To Integer a Bitmask...:
>>> int('00100101',2)
>>> 37
To Bitmask an 8 bit Integer...:
def int2bitmask(some_int):
bitmask = ""
octal_dict={'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','7':'111'}
for c in oct(some_int)[1:]:
bitmask = bitmask+octal_dict[c]
return bitmask.lstrip('0').rjust(8,'0')
To Turn Some ASCII HEX into binary data suitable for transfer over the wire...:
command = "AA AA AA 11 11 11 00 11 FF"
def ascii2hex(command):
bytes = command.split()
binary_bytes = [chr(int(byte,16)) for byte in bytes]
binary = "".join(binary_bytes)
print repr(binary) ##just to be sure...
return(binary)
>>> '\xaa\xaa\xaa\x11\x11\x11\x00\x11\xff'
Here's Another method using the module binascii (check it out!)
import binascii
command = "AA AA AA 11 11 11 00 11 FF"
def ascii2hex(command):
bytes = command.replace(' ','')
binary = binascii.unhexlify(bytes) ##turns the hex to binary
print repr(binary) ## just to be sure...
print "Binary to be sent: ", binascii.hexlify(binary) ## pretty prints the binary - similar to repr(binary)
return(binary)
>>>'\xaa\xaa\xaa\x11\x11\x11\x00\x11\xff'
«
Last Edit: May 27, 2010, 09:02:41 AM by webmaster
»
Report to moderator
Logged
Pages: [
1
]
Print
« previous
next »
Jump to:
Please select a destination:
-----------------------------
General Category
-----------------------------
=> PSE Discussion Forum
-----------------------------
Development
-----------------------------
=> Python
Loading...