[Tutor] bit shifting

Ian D duxbuz at hotmail.com
Thu May 1 10:08:17 CEST 2014


I am trying to follow some code. It is basically a python scratch interfacing script.



Anyway part of the script has this code.



Searching google for >> greater than signs in code with python has its issues. 



Can anyone clarify this stuff.



I know its about 4 bytes of data. It looks like its setting all bits HIGH to me?       



n = len(cmd)
a = array('c')
a.append(chr((n>> 24) & 0xFF))
a.append(chr((n>> 16) & 0xFF))
a.append(chr((n>>  8) & 0xFF))
a.append(chr(n & 0xFF))





More code for context for python version 2.7:



from array import array
   import socket
   import time
   import sys
   
   from Tkinter import Tk
   from tkSimpleDialog import askstring
   root = Tk()
   root.withdraw()
   
   PORT = 42001
   HOST = askstring('Scratch Connector', 'IP:')
   if not HOST:
       sys.exit()
   
   print("Connecting...")
   scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   scratchSock.connect((HOST, PORT))
   print("Connected!")
   
   def sendScratchCommand(cmd):
       n = len(cmd)
       a = array('c')
       a.append(chr((n>> 24) & 0xFF))
       a.append(chr((n>> 16) & 0xFF))
       a.append(chr((n>>  8) & 0xFF))
       a.append(chr(n & 0xFF))
       scratchSock.send(a.tostring() + cmd)
   
   while True:
       msg = askstring('Scratch Connector', 'Send Broadcast:')
       if msg:
           sendScratchCommand('broadcast "' + msg + '"')



Another for Python 3:

import socket

HOST = 'localhost'
PORT = 42001

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

def sendCMD(cmd):
    n = len(cmd)
    a = []
    a.append((n>> 24) & 0xFF)
    a.append((n>> 16) & 0xFF)
    a.append((n>> 8) & 0xFF)
    a.append(n & 0xFF)
    b = ''
    for i in list(range(len(a))):
        b  += a[i]
    s.send(bytes(b+cmd,'UTF-8'))

sendCMD('broadcast"hello"') 		 	   		  


More information about the Tutor mailing list