Reputation: 87
I'm currently trying to build a RDP client in python and I came across the following issue with a len check;
From: http://msdn.microsoft.com/en-us/library/cc240836%28v=prot.10%29.aspx
81 2a -> ConnectData::connectPDU length = 298 bytes Since the most significant bit of the first byte (0x81) is set to 1 and the following bit is set to 0, the length is given by the low six bits of the first byte and the second byte. Hence, the value is 0x12a, which is 298 bytes.
This sounds weird.
For normal len checks, I'm simply using : struct.pack(">h",len(str(PacketLen)))
but in this case, I really don't see how I can calculate the len as described above.
Any help on this would be greatly appreciated !
Upvotes: 0
Views: 548
Reputation: 601599
Just set the most-significant bit by using a bitwise OR:
struct.pack(">H", len(...) | 0x8000)
You might want to add a check to make sure the length fits into 14 bits, i.e. it is less than 2 ** 14
.
Edit: Fixed according to the comment by TokenMacGuy.
Upvotes: 1
Reputation: 11730
Not a terribly uncommon scenario when dealing with bandwidth sensitive transmission protocols. They are basically saying if the length that follows fit in the range of 0 -> 0x7F, just use one byte, otherwise, you can optionally use 2-bytes. (note: the largest legal value with this system is therefore 16,383)
Here's a quick example:
if len <= 0x7F:
pkt = struct.pack('B', len)
elif len <= 0x3FFF:
pkt = struct.pack('>h', len | 0x8000)
else:
raise ValueError('length exceeds maxvalue')
Upvotes: 0