code: public static int encodeBitString(BitSet value, int nbits, ByteBuffer buf) {
          if (value == null || nbits < value.length()) {
              throw new IllegalArgumentException();
          }
  
          int pos = buf.position();
          int contentLength = (int) Math.ceil(nbits / 8.0d);
          for (int i = contentLength; i > 0; i--) {
              byte octet = 0;
              for (int j = (i - 1) * 8; j < i * 8; j++) {
                  if (value.get(j)) {
                      octet |= BIT_STRING_MASK[j % 8];
                  }
              }
              pos--;
              buf.put(pos, octet);
          }
  
          // Write out padding byte (primitive encoding)
          pos--;
          buf.put(pos, (byte) 0);
          contentLength++;
  
          buf.position(buf.position() - contentLength);
          int headerLength = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE,
                  ASN1_BIT_STRING_TAG_NUM, contentLength, buf);
          return headerLength + contentLength;
      }
docs: Encode an ASN.1 BIT STRING.
  
  @param value
  the value to be encoded
  @param nbits
  the number of bits in the bit string
  @param buf
  the buffer with space to the left of current position where the value will be encoded
  @return the length of the encoded data