Jun 12, 2018

I had an issue recently where I needed to write some bits into a byte array in network order. In my case, I was writing an executable which could read a text file with some instructions on what to write into a network packet, then send that packet over the network.

// Here is an explanation:
//
// Say we have our buffer, which is 1 byte long:
// ^
// buffer -> 00000000
//
// Now we want to write a 2 bit long value into it, which has the value 3 (binary 11).
// ^
// Now buffer -> 11000000
// Now lets write another value, this time 3 bits, with the value zero.
// ^
// Now buffer -> 11000000
// Now lets write another 2 bit value, but this time with the value 1. (binary 01).
// ^
// Now buffer -> 11000010
//
// He is an example for an ethernet frame
//
// An ethernet frame is laid out as follows:
//
// Destination MAC Address: 48 bits
// Source MAC Address: 48 bits
// Ethernet Type: 16 bits
//
// I wanted to be able to create a file which had some sort
// of details like this, very generalized.
//
// For example:
// 0x00155E112233 int48
// 0x00155E445566 int48
// 0x0800 int16
//
// This would write an ethernet frame into a byte[] buffer. There are some more
// complex cases in the IPv4 header, which need to write values that are 2 or 4 bits long.
//

That's where this bit of code was born. It takes a list of values and their bit length as an input, and writes them into a bit buffer.