public static function bitstringToHex($bitstring)
    {
        $chunkSizeBits = 8;

        // If the string is shorter than the chunk size it can be 0-padded
        if (strlen($bitstring) < $chunkSizeBits) {
            $bitstring = str_pad($bitstring, $chunkSizeBits, '0', STR_PAD_LEFT);
        }

        if (strlen($bitstring) % $chunkSizeBits !== 0) throw new \InvalidArgumentException(sprintf('Got bitstring of length %s, but it must be divisible by %s', strlen($bitstring), $chunkSizeBits));

        $finalHex = '';
        for ($i=0; $i < strlen($bitstring); $i += $chunkSizeBits) {
            $bitstringPart = substr($bitstring, $i, $chunkSizeBits);
            $hex = base_convert($bitstringPart, 2, 16);
            // Ensure hex is always two characters
            $hex = str_pad($hex, 2, '0', STR_PAD_LEFT);

            $finalHex .= $hex;
        }

        return $finalHex;
    }