PSE Entertainment Corp
May 21, 2012, 01:40:48 AM *
Welcome, Guest. Please login or register.

Login with username, password and session length
News: Enjoy PSE Tunes!  They're great!
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: Python - Bit and Byte Twiddling  (Read 3785 times)
webmast
Guest
« 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  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.14 | SMF © 2006-2008, Simple Machines LLC Valid XHTML 1.0! Valid CSS!