code: public static byte[] encodeLength(int length)
      {
          if (length < 128) {
              return new byte[] {(byte) length};
          }
          int numberOfBits = 32 - Integer.numberOfLeadingZeros(length);
          int numberOfBytes = (numberOfBits + 7) / 8;
          byte[] encoded = new byte[1 + numberOfBytes];
          encoded[0] = (byte) (numberOfBytes | 0x80);
          for (int i = 0; i < numberOfBytes; i++) {
              int byteToEncode = (numberOfBytes - i);
              int shiftSize = (byteToEncode - 1) * 8;
              encoded[i + 1] = (byte) (length >>> shiftSize);
          }
          return encoded;
      }
docs: Encodes the length of a DER value.  The encoding of a 7bit value is simply the value.  Values needing more than 7bits
  are encoded as a lead byte with the high bit set and containing the number of value bytes.  Then the following bytes
  encode the length using the least number of bytes possible.