Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[paho-dev] [PATCH] MQTTPacket: Improved length encoding

Improved length encoding by doing-away with division. On my system this
runs roughly twice as fast. On micro-processors that do not have an
inbuilt division instruction this should increase performance quite
significantly.

I cross-checked the output with the previous implementation and it seems
to match up perfectly, though further testing &/or suggestions are appreciated.

---
 MQTTPacket/src/MQTTPacket.c | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)

diff --git a/MQTTPacket/src/MQTTPacket.c b/MQTTPacket/src/MQTTPacket.c
index 4f1f95a..78eb5a6 100644
--- a/MQTTPacket/src/MQTTPacket.c
+++ b/MQTTPacket/src/MQTTPacket.c
@@ -31,15 +31,16 @@ int MQTTPacket_encode(unsigned char* buf, int length)
 	int rc = 0;
 
 	FUNC_ENTRY;
-	do
-	{
-		char d = length % 128;
-		length /= 128;
-		/* if there are more digits to encode, set the top bit of this digit */
-		if (length > 0)
-			d |= 0x80;
-		buf[rc++] = d;
-	} while (length > 0);
+	for(rc = 0; rc < 4; rc++) {
+		buf[rc] |= (length & 0x7F); /* 01111111 */
+		length = (length >> 7);
+		if (length) {
+			buf[rc] |= 0x80;
+		}
+		else {
+			break;
+		}
+	}
 	FUNC_EXIT_RC(rc);
 	return rc;
 }
-- 
2.24.0



Back to the top