Reputation: 3
So basically i have this piece of code that i have found into someone else's code and works fine for the thing i'm trying to do but i will like to understand how it works.
I wanna know how it differences from writting an uint32 into an array like using Uint8Array and writing inside the Uint32Array buffer or using a DataView with setUint32 doesn't gives the same result
function writeUint32(message, value){
while(true){
if((value & -128) === 0){
message.push(value)
return
}
else {
message.push(value & 127 | 128)
value >>>= 7
}
}
}
Upvotes: 0
Views: 340
Reputation: 64913
The difference is that this function writes the value in a variable length format, using 7 bits of data per byte and 1 bit to signal that more data follows, in little endian order (the first byte contains the low order bits). This is known as LEB128. setUint32
on a DataView just copies the bits straight to the underlying array without fancy encoding. LEB128 (or other variable length encoding) can be used to save space (if the encoded values are not typically high) but costs a little bit of extra work to encode and decode.
To explain the code,
(value & -128) === 0
This checks if the top 25 bits are all zero, if they are then the current value fits in a 7 bit chunk and that will be the final chunk (the "continue" flag is not set).
value & 127 | 128
This takes the least significant 7 bits from the value, and then sets the "continue" flag on the resulting chunk.
value >>>= 7
Then drop the bits we just encoded and continue with the higher bits of the value.
Upvotes: 1