Skip to main content
Module

x/protocol/util/util.js

A JavaScript library for parsing and serializing Minecraft client-server packets.
Latest
File
// takes an array of bytes and returns the first varint that// it can find and the number of bytes it read, varints are// encoded using LEN128export function readVarInt(bytes) { let mask128 = 128 // 10000000 let varIntSize = 0 for (let i = 0; i < bytes.length; i++) { if ((bytes[i] & mask128) > 0) { varIntSize++ } else { varIntSize++ break } }
let varInt = 0 let mask127 = 127 // 01111111
for (let i = 0; i < varIntSize; i++) { varInt += (bytes[i] & mask127) << (i * 7) }
return { varInt, varIntSize }}
// takes an integer, encodes it using LEN128 and returns// the byte array result as a Uint8Arrayexport function makeVarInt(num) { let numberOfBits = 0
for (let i = 0; i < 64; i++) { if ((num >>> i) > 0) { numberOfBits++ } else { numberOfBits++ break } }
let varIntBytes = new Uint8Array(Math.floor(numberOfBits / 7) + 1) let mask128 = 128 // 100000000 for (let i = 0; i < varIntBytes.length; i++) { varIntBytes[i] = (num >>> (i * 7)) | mask128 }
let mask127 = 127 // 01111111 varIntBytes[varIntBytes.length-1] = varIntBytes[varIntBytes.length-1] & mask127
return varIntBytes}