[Tutor] bit shifting
Ian D
duxbuz at hotmail.com
Thu May 1 11:53:15 CEST 2014
Ok I am getting somewhere with this now.
A bitshift followed by ANDing the result of the shift!
So I think n>> 24 & 0xFF
is
shift n 3 bytes right, save results in n and then AND n with 255 decimal?
----------------------------------------
> From: duxbuz at hotmail.com
> To: tutor at python.org
> Date: Thu, 1 May 2014 08:08:17 +0000
> Subject: [Tutor] bit shifting
>
> 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"')
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list