简体   繁体   中英

Extracting/Shifting bits in python for websocket RFC 6455

I am trying to implement my own Websocket server in python im following the RFC 6455 Spec and im running into problems extracting the bits from the Base Frame header

im not having problems with the protocol im having problems with basic binary/hex math magic

according to the Specs the first 4 bits are single bit values

so to get the first bit i do something like this (d being my data from the websocket)

first_byte = ord(d[0])
print "finished bit",(first_byte >> 7) & 1

and later on if i want to get the payload size i do

sec_byte = ord(d[1])
print "payload size",sec_byte & 0x7f

however later in the spec i need to grab a 4bit value for the opcodes this is what i need help on maybe even a link to how this math works ive googled/duckduckgoed my brains out most results being from stackoverflow

even more tinkering and its starting to fall into place i had been stuck on this for about 4 days now and still unsolved for anymore info anyone can give.

If you need to consider only the first (Most Significant) 4 bits, you need to right shift by 4 (extra masking with And could be unuseful, eg if your value is in the range 0-255, but it even stresses the bits you're are interested in). Eg

>>> d = [128, 80, 40]
>>> print (d[0] >> 4) & 15
8
>>> print (d[1] >> 4) & 15
5
>>> print (d[2] >> 4) & 15
2

128 is in binary 1000 0000 ; right shifting by 4 gives 0000 1000 ("new" 0 bits enter from left), ie 8; 80 is 0101 0000 , so you obtain 0000 0101 ; and finally 40 is 0010 1000 and we obtain 0000 0010 .

In general, consider an octet like abcd efgh where each letter is a bit. You have to shift and And in order to isolate the bits you are interested in. Eg suppose your spec says cd bits define four different kind of something. In order to obtain that 0-3 number, you right shift by 4 again, and and with 3, that is 0000 0011 , ie you "isolate" the bits you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM