简体   繁体   English

为Websocket RFC 6455在python中提取/移位位

[英]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 我正在尝试按照RFC 6455规范在python im中实现我自己的Websocket服务器,并且im遇到了从Base Frame标头中提取位的问题

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 根据规格,前4位是单个位值

so to get the first bit i do something like this (d being my data from the websocket) 为了得到第一点,我要做这样的事情(d是我从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 但是在以后的规范中,我需要为操作码获取一个4bit的值,这是我需要的帮助,甚至可能需要链接到此数学方法的工作方式googled / duckduck导致我的大脑大部分结果来自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. 甚至更动手了,它开始就位了,我在此问题上停留了大约4天,但对于任何人都可以提供的任何信息仍然无法解决。

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). 如果只需要考虑前4位(最高有效位),则需要右移4位(用And进行额外的掩码可能会无用,例如,如果您的值在0-255范围内,但它甚至会给您带来压力)有兴趣)。 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 ; 128是二进制1000 0000 ; right shifting by 4 gives 0000 1000 ("new" 0 bits enter from left), ie 8; 向右移动4可获得0000 1000 (“新” 0位从左输入),即8; 80 is 0101 0000 , so you obtain 0000 0101 ; 80是0101 0000 ,因此您得到0000 0101 and finally 40 is 0010 1000 and we obtain 0000 0010 . 最后40是0010 1000 ,我们得到0000 0010

In general, consider an octet like abcd efgh where each letter is a bit. 通常,考虑一个像abcd efgh这样的八位字节,其中每个字母都是一点。 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. 您必须移动和并且才能分离出您感兴趣的位。例如,假设您的规范说cd位定义了四种不同的东西。 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. 为了获得该0-3数字,请再次右移4,然后再右移3,即0000 0011 ,即“隔离”所需的位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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