Shadebob Games

Yet another game development blog

Bit packing in JAVA

Yesterday I took time to write a small utility class to handle bit packing for my upcoming game network protocol.

Bit packing is a must have when you implement a network protocol. Here is an example usage:

Let's say you have a byte that contains the current player slot position. This is a 4 players game, then you have 0,1,2,3 as positions. Using a whole byte (8 bits) to store the position is not optimal, you can store the same value in 2 bits.

This might not look that much but if you are sending 20-60 packets per second, it is starting to count bandwidth-wise.

Here is how to use the class:

BitPacker packer = new BitPacker();  
int playerPosition = 4;  
packer.putInt(playerPosition, 2); // It will put the first two bits of the int in a bitset  

packer.toBytes() returns the bytes to send via network (the content will be padded with zeroes to match 8 bits multiple)

Now let see the reverse, when you receive the data from network as byte[]:

BitPacker packer = new BitPacker();  
int playerPosition = packer.getInteger(2);  
System.out.println("Player position: " + playerPosition); // Should be 4.  

If you want to re-use the same BitPacker object, you can call reset() and rewind().

Here is the link for the code:

This article was posted by Yanick Bourbeau & It's my 10th oldest. It is 213 words long.
comments powered by Disqus