Automatically right pad with null bytes an ecc to fill for missing bytes if too small, or leave unchanged if not necessary. This can be used as a workaround for field delimiter misdetection. Equivalent to puncturing (punctured reed-solomon code).
977661
def rpad(self, ecc, k=None):
        ''''''
        if not k: k = self.k
        pad = None
        if len(ecc) < self.n-k:
            print("Warning: the ecc field may have been truncated (entrymarker or field_delim misdetection?).")
            #pad = "\x00" * (self.n-k-len(ecc))
            pad = bytearray(self.n-k-len(ecc))
            ecc = ecc + pad
        return [ecc, pad]
545499
static ByteString unescapeBytes(final CharSequence charString)
      throws InvalidEscapeSequenceException {
    // First convert the Java character sequence to UTF-8 bytes.
    ByteString input = ByteString.copyFromUtf8(charString.toString());
    // Then unescape certain byte sequences introduced by ASCII '\\'.  The valid
    // escapes can all be expressed with ASCII characters, so it is safe to
    // operate on bytes here.
    //
    // Unescaping the input byte array will result in a byte sequence that's no
    // longer than the input.  That's because each escape sequence is between
    // two and four bytes long and stands for a single byte.
    final byte[] result = new byte[input.size()];
    int pos = 0;
    for (int i = 0; i < input.size(); i++) {
      byte c = input.byteAt(i);
      if (c == '\\') {
        if (i + 1 < input.size()) {
          ++i;
          c = input.byteAt(i);
          if (isOctal(c)) {
            // Octal escape.
            int code = digitValue(c);
            if (i + 1 < input.size() && isOctal(input.byteAt(i + 1))) {
              ++i;
              code = code * 8 + digitValue(input.byteAt(i));
            }
            if (i + 1 < input.size() && isOctal(input.byteAt(i + 1))) {
              ++i;
              code = code * 8 + digitValue(input.byteAt(i));
            }
            // TODO: Check that 0 <= code && code <= 0xFF.
            result[pos++] = (byte)code;
          } else {
            switch (c) {
              case 'a' : result[pos++] = 0x07; break;
              case 'b' : result[pos++] = '\b'; break;
              case 'f' : result[pos++] = '\f'; break;
              case 'n' : result[pos++] = '\n'; break;
              case 'r' : result[pos++] = '\r'; break;
              case 't' : result[pos++] = '\t'; break;
              case 'v' : result[pos++] = 0x0b; break;
              case '\\': result[pos++] = '\\'; break;
              case '\'': result[pos++] = '\''; break;
              case '"' : result[pos++] = '\"'; break;

              case 'x':
                // hex escape
                int code = 0;
                if (i + 1 < input.size() && isHex(input.byteAt(i + 1))) {
                  ++i;
                  code = digitValue(input.byteAt(i));
                } else {
                  throw new InvalidEscapeSequenceException(
                      "Invalid escape sequence: '\\x' with no digits");
                }
                if (i + 1 < input.size() && isHex(input.byteAt(i + 1))) {
                  ++i;
                  code = code * 16 + digitValue(input.byteAt(i));
                }
                result[pos++] = (byte)code;
                break;

              default:
                throw new InvalidEscapeSequenceException(
                    "Invalid escape sequence: '\\" + (char)c + '\'');
            }
          }
        } else {
          throw new InvalidEscapeSequenceException(
              "Invalid escape sequence: '\\' at end of string.");
        }
      } else {
        result[pos++] = c;
      }
    }

    return ByteString.copyFrom(result, 0, pos);
  }
106929
function des_addPadding(message, padding) {
  const padLength = 8 - (message.length % 8);

  let pad;
  if (padding === 2 && (padLength < 8)) { //pad the message with spaces
    pad = " ".charCodeAt(0);
  } else if (padding === 1) { //PKCS7 padding
    pad = padLength;
  } else if (!padding && (padLength < 8)) { //pad the message out with null bytes
    pad = 0;
  } else if (padLength === 8) {
    return message;
  } else {
    throw new Error('des: invalid padding');
  }

  const paddedMessage = new Uint8Array(message.length + padLength);
  for (let i = 0; i < message.length; i++) {
    paddedMessage[i] = message[i];
  }
  for (let j = 0; j < padLength; j++) {
    paddedMessage[message.length + j] = pad;
  }

  return paddedMessage;
}
514934
private int bufferCrypt(ByteBuffer input, ByteBuffer output,
            boolean isUpdate) throws ShortBufferException,
            IllegalBlockSizeException, BadPaddingException {
        if ((input == null) || (output == null)) {
            throw new NullPointerException
                ("Input and output buffers must not be null");
        }
        int inPos = input.position();
        int inLimit = input.limit();
        int inLen = inLimit - inPos;
        if (isUpdate && (inLen == 0)) {
            return 0;
        }
        int outLenNeeded = engineGetOutputSize(inLen);
        if (output.remaining() < outLenNeeded) {
            throw new ShortBufferException("Need at least " + outLenNeeded
                + " bytes of space in output buffer");
        }

        boolean a1 = input.hasArray();
        boolean a2 = output.hasArray();

        if (a1 && a2) {
            byte[] inArray = input.array();
            int inOfs = input.arrayOffset() + inPos;
            byte[] outArray = output.array();
            int outPos = output.position();
            int outOfs = output.arrayOffset() + outPos;
            int n;
            if (isUpdate) {
                n = engineUpdate(inArray, inOfs, inLen, outArray, outOfs);
            } else {
                n = engineDoFinal(inArray, inOfs, inLen, outArray, outOfs);
            }
            input.position(inLimit);
            output.position(outPos + n);
            return n;
        } else if (!a1 && a2) {
            int outPos = output.position();
            byte[] outArray = output.array();
            int outOfs = output.arrayOffset() + outPos;
            byte[] inArray = new byte[getTempArraySize(inLen)];
            int total = 0;
            do {
                int chunk = Math.min(inLen, inArray.length);
                if (chunk > 0) {
                    input.get(inArray, 0, chunk);
                }
                int n;
                if (isUpdate || (inLen != chunk)) {
                    n = engineUpdate(inArray, 0, chunk, outArray, outOfs);
                } else {
                    n = engineDoFinal(inArray, 0, chunk, outArray, outOfs);
                }
                total += n;
                outOfs += n;
                inLen -= chunk;
            } while (inLen > 0);
            output.position(outPos + total);
            return total;
        } else { // output is not backed by an accessible byte[]
            byte[] inArray;
            int inOfs;
            if (a1) {
                inArray = input.array();
                inOfs = input.arrayOffset() + inPos;
            } else {
                inArray = new byte[getTempArraySize(inLen)];
                inOfs = 0;
            }
            byte[] outArray = new byte[getTempArraySize(outLenNeeded)];
            int outSize = outArray.length;
            int total = 0;
            boolean resized = false;
            do {
                int chunk =
                    Math.min(inLen, (outSize == 0? inArray.length : outSize));
                if (!a1 && !resized && chunk > 0) {
                    input.get(inArray, 0, chunk);
                    inOfs = 0;
                }
                try {
                    int n;
                    if (isUpdate || (inLen != chunk)) {
                        n = engineUpdate(inArray, inOfs, chunk, outArray, 0);
                    } else {
                        n = engineDoFinal(inArray, inOfs, chunk, outArray, 0);
                    }
                    resized = false;
                    inOfs += chunk;
                    inLen -= chunk;
                    if (n > 0) {
                        output.put(outArray, 0, n);
                        total += n;
                    }
                } catch (ShortBufferException e) {
                    if (resized) {
                        // we just resized the output buffer, but it still
                        // did not work. Bug in the provider, abort
                        throw (ProviderException)new ProviderException
                            ("Could not determine buffer size").initCause(e);
                    }
                    // output buffer is too small, realloc and try again
                    resized = true;
                    outSize = engineGetOutputSize(chunk);
                    outArray = new byte[outSize];
                }
            } while (inLen > 0);
            if (a1) {
                input.position(inLimit);
            }
            return total;
        }
    }
832487
function pctCharAt(text, startIndex) {
        var chr = text.charAt(startIndex);
        if (!isPercentDigitDigit(text, startIndex)) {
            return chr;
        }
        var utf8CharCode = parseHex2(text, startIndex + 1);
        var numBytes = utf8.numBytes(utf8CharCode);
        if (numBytes === 0) {
            return chr;
        }
        for (var byteNumber = 1; byteNumber < numBytes; byteNumber += 1) {
            if (!isPercentDigitDigit(text, startIndex + 3 * byteNumber) || !utf8.isValidFollowingCharCode(parseHex2(text, startIndex + 3 * byteNumber + 1))) {
                return chr;
            }
        }
        return text.substr(startIndex, 3 * numBytes);
    }
1358471
def skipNullPadding(self, buff):
        '''
        
        '''
        def readNext(buff, first_run=True):
            datas = unpack('<i', buff.read(4))
            header = datas[0]

            if header == CHUNK_NULL_TYPE and first_run:
                print("Skipping null padding in StringPoolChunk header")
                header = readNext(buff, first_run=False)
            elif header != CHUNK_STRINGPOOL_TYPE:
                print("Invalid StringPoolChunk header")

            return header

        header = readNext(buff)
        return header >> 8, header & 0xFF
701109
function padLeft(val, len, offset, char) {
    /* istanbul ignore if */
    if (!is_1.isValue(val) || !is_1.isString(val))
        return null;
    // If offset is a string
    // count its length.
    if (is_1.isString(offset))
        offset = offset.length;
    char = char || ' ';
    var pad = '';
    while (len--) {
        pad += char;
    }
    if (offset)
        return padLeft('', offset, null, char) + pad + val;
    return pad + val;
}
672883
private void qrBinary(int[] datastream, int version, int target_binlen, QrMode[] inputMode, int[] inputData, boolean gs1, int eciMode, int est_binlen) {

        // TODO: make encodeInfo a StringBuilder, make this method static?

        int position = 0;
        int short_data_block_length, i;
        int padbits;
        int current_binlen, current_bytes;
        int toggle;
        QrMode data_block;

        StringBuilder binary = new StringBuilder(est_binlen + 12);

        if (gs1) {
            binary.append("0101"); /* FNC1 */
        }

        if (eciMode != 3) {
            binary.append("0111"); /* ECI (Table 4) */
            if (eciMode <= 127) {
                binaryAppend(eciMode, 8, binary); /* 000000 to 000127 */
            } else if (eciMode <= 16383) {
                binaryAppend(0x8000 + eciMode, 16, binary); /* 000000 to 016383 */
            } else {
                binaryAppend(0xC00000 + eciMode, 24, binary); /* 000000 to 999999 */
            }
        }

        encodeInfo += "Encoding: ";

        do {
            data_block = inputMode[position];
            short_data_block_length = 0;
            do {
                short_data_block_length++;
            } while (((short_data_block_length + position) < inputMode.length)
                    && (inputMode[position + short_data_block_length] == data_block));

            switch (data_block) {

                case KANJI:
                    /* Kanji mode */
                    /* Mode indicator */
                    binary.append("1000");

                    /* Character count indicator */
                    binaryAppend(short_data_block_length, tribus(version, 8, 10, 12), binary);

                    encodeInfo += "KNJI ";

                    /* Character representation */
                    for (i = 0; i < short_data_block_length; i++) {
                        int jis = inputData[position + i];
                        if (jis >= 0x8140 && jis <= 0x9ffc) {
                            jis -= 0x8140;
                        } else if (jis >= 0xe040 && jis <= 0xebbf) {
                            jis -= 0xc140;
                        }
                        int prod = ((jis >> 8) * 0xc0) + (jis & 0xff);
                        binaryAppend(prod, 13, binary);
                        encodeInfo += Integer.toString(prod) + " ";
                    }

                    break;

                case BINARY:
                    /* Byte mode */
                    /* Mode indicator */
                    binary.append("0100");

                    /* Character count indicator */
                    binaryAppend(short_data_block_length, tribus(version, 8, 16, 16), binary);

                    encodeInfo += "BYTE ";

                    /* Character representation */
                    for (i = 0; i < short_data_block_length; i++) {
                        int b = inputData[position + i];
                        if (b == FNC1) {
                            b = 0x1d; /* FNC1 */
                        }
                        binaryAppend(b, 8, binary);
                        encodeInfo += Integer.toString(b) + " ";
                    }

                    break;

                case ALPHANUM:
                    /* Alphanumeric mode */
                    /* Mode indicator */
                    binary.append("0010");

                    /* If in GS1 mode, expand FNC1 -> '%' and expand '%' -> '%%' in a new array */
                    int percentCount = 0;
                    if (gs1) {
                        for (i = 0; i < short_data_block_length; i++) {
                            if (inputData[position + i] == '%') {
                                percentCount++;
                            }
                        }
                    }
                    int[] inputExpanded = new int[short_data_block_length + percentCount];
                    percentCount = 0;
                    for (i = 0; i < short_data_block_length; i++) {
                        int c = inputData[position + i];
                        if (c == FNC1) {
                            inputExpanded[i + percentCount] = '%'; /* FNC1 */
                        } else {
                            inputExpanded[i + percentCount] = c;
                            if (gs1 && c == '%') {
                                percentCount++;
                                inputExpanded[i + percentCount] = c;
                            }
                        }
                    }

                    /* Character count indicator */
                    binaryAppend(inputExpanded.length, tribus(version, 9, 11, 13), binary);

                    encodeInfo += "ALPH ";

                    /* Character representation */
                    for (i = 0; i + 1 < inputExpanded.length; i += 2) {
                        int first = positionOf((char) inputExpanded[i], RHODIUM);
                        int second = positionOf((char) inputExpanded[i + 1], RHODIUM);
                        int prod = (first * 45) + second;
                        int count = 2;
                        binaryAppend(prod, 1 + (5 * count), binary);
                        encodeInfo += Integer.toString(prod) + " ";
                    }
                    if (inputExpanded.length % 2 != 0) {
                        int first = positionOf((char) inputExpanded[inputExpanded.length - 1], RHODIUM);
                        int prod = first;
                        int count = 1;
                        binaryAppend(prod, 1 + (5 * count), binary);
                        encodeInfo += Integer.toString(prod) + " ";
                    }

                    break;

                case NUMERIC:
                    /* Numeric mode */
                    /* Mode indicator */
                    binary.append("0001");

                    /* Character count indicator */
                    binaryAppend(short_data_block_length, tribus(version, 10, 12, 14), binary);

                    encodeInfo += "NUMB ";

                    /* Character representation */
                    i = 0;
                    while (i < short_data_block_length) {

                        int first = Character.getNumericValue(inputData[position + i]);
                        int count = 1;
                        int prod = first;

                        if (i + 1 < short_data_block_length) {
                            int second = Character.getNumericValue(inputData[position + i + 1]);
                            count = 2;
                            prod = (prod * 10) + second;

                            if (i + 2 < short_data_block_length) {
                                int third = Character.getNumericValue(inputData[position + i + 2]);
                                count = 3;
                                prod = (prod * 10) + third;
                            }
                        }

                        binaryAppend(prod, 1 + (3 * count), binary);

                        encodeInfo += Integer.toString(prod) + " ";

                        i += count;
                    };

                    break;
            }

            position += short_data_block_length;

        } while (position < inputMode.length);

        encodeInfo += "\n";

        /* Terminator */
        binary.append("0000");

        current_binlen = binary.length();
        padbits = 8 - (current_binlen % 8);
        if (padbits == 8) {
            padbits = 0;
        }
        current_bytes = (current_binlen + padbits) / 8;

        /* Padding bits */
        for (i = 0; i < padbits; i++) {
            binary.append('0');
        }

        /* Put data into 8-bit codewords */
        for (i = 0; i < current_bytes; i++) {
            datastream[i] = 0x00;
            for (int p = 0; p < 8; p++) {
                if (binary.charAt((i * 8) + p) == '1') {
                    datastream[i] += (0x80 >> p);
                }
            }
        }

        /* Add pad codewords */
        toggle = 0;
        for (i = current_bytes; i < target_binlen; i++) {
            if (toggle == 0) {
                datastream[i] = 0xec;
                toggle = 1;
            } else {
                datastream[i] = 0x11;
                toggle = 0;
            }
        }

        encodeInfo += "Codewords: ";
        for (i = 0; i < target_binlen; i++) {
            encodeInfo += Integer.toString(datastream[i]) + " ";
        }
        encodeInfo += "\n";
    }
1161964
def encode_sequence(content, error=None, version=None, mode=None,
                    mask=None, encoding=None, eci=False, boost_error=True,
                    symbol_count=None):
    
    def one_item_segments(chunk, mode):
        """\
        Creates a Segments sequence with one item.
        """
        segs = Segments()
        segs.add_segment(make_segment(chunk, mode=mode, encoding=encoding))
        return segs

    def divide_into_chunks(data, num):
        k, m = divmod(len(data), num)
        return [data[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(num)]

    def calc_qrcode_bit_length(char_count, ver_range, mode, encoding=None,
                               is_eci=False, is_sa=False):
        overhead = 4  # Mode indicator for QR Codes, only
        # Number of bits in character count indicator
        overhead += consts.CHAR_COUNT_INDICATOR_LENGTH[mode][ver_range]
        if is_eci and mode == consts.MODE_BYTE and encoding != consts.DEFAULT_BYTE_ENCODING:
            overhead += 4  # ECI indicator
            overhead += 8  # ECI assignment no
        if is_sa:
            # 4 bit for mode, 4 bit for the position, 4 bit for total number of symbols
            # 8 bit for parity data
            overhead += 5 * 4
        bits = 0
        if mode == consts.MODE_NUMERIC:
            num, remainder = divmod(char_count, 3)
            bits += num * 10 + (4 if remainder == 1 else 7)
        elif mode == consts.MODE_ALPHANUMERIC:
            num, remainder = divmod(char_count, 2)
            bits += num * 11 + (6 if remainder else 0)
        elif mode == consts.MODE_BYTE:
            bits += char_count * 8
        elif mode == consts.MODE_KANJI:
            bits += char_count * 13
        return overhead + bits

    def number_of_symbols_by_version(content, version, error, mode):
        """\
        Returns the number of symbols for the provided version.
        """
        length = len(content)
        ver_range = version_range(version)
        bit_length = calc_qrcode_bit_length(length, ver_range, mode, encoding,
                                            is_eci=eci, is_sa=True)
        capacity = consts.SYMBOL_CAPACITY[version][error]
        # Initial result does not contain the overhead of SA mode for all QR Codes
        cnt = int(math.ceil(bit_length / capacity))
        # Overhead of SA mode for all QR Codes
        bit_length += 5 * 4 * (cnt - 1) + (12 * (cnt - 1) if eci else 0)
        return int(math.ceil(bit_length / capacity))

    version = normalize_version(version)
    if version is not None:
        if version < 1:
            raise VersionError('This function does not accept Micro QR Code versions. '
                               'Provided: "{0}"'.format(get_version_name(version)))
    elif symbol_count is None:
        raise ValueError('Please provide a QR Code version or the symbol count')
    if symbol_count is not None and not 1 <= symbol_count <= 16:
        raise ValueError('The symbol count must be in range 1 .. 16')
    error = normalize_errorlevel(error, accept_none=True)
    if error is None:
        error = consts.ERROR_LEVEL_L
    mode = normalize_mode(mode)
    mask = normalize_mask(mask, is_micro=False)
    segments = prepare_data(content, mode, encoding, version)
    guessed_version = None
    if symbol_count is None:
        try:
            # Try to find a version which fits without using Structured Append
            guessed_version = find_version(segments, error, eci=eci, micro=False)
        except DataOverflowError:
            # Data does fit into a usual QR Code but ignore the error silently,
            # guessed_version is None
            pass
        if guessed_version and guessed_version <= (version or guessed_version):
            # Return iterable of size 1
            return [_encode(segments, error=error, version=(version or guessed_version),
                            mask=mask, eci=eci, boost_error=boost_error)]
    if len(segments.modes) > 1:
        raise ValueError('This function cannot handle more than one mode (yet). Sorry.')
    mode = segments.modes[0]  # CHANGE iff more than one mode is supported!
    # Creating one QR code failed or max_no is not None
    if mode == consts.MODE_NUMERIC:
        content = str(content)
    if symbol_count is not None and len(content) < symbol_count:
        raise ValueError('The content is not long enough to be divided into {0} symbols'.format(symbol_count))
    sa_parity_data = calc_structured_append_parity(content)
    num_symbols = symbol_count or 16
    if version is not None:
        num_symbols = number_of_symbols_by_version(content, version, error, mode)
    if num_symbols > 16:
        raise DataOverflowError('The data does not fit into Structured Append version {0}'.format(version))
    chunks = divide_into_chunks(content, num_symbols)
    if symbol_count is not None:
        segments = one_item_segments(max(chunks, key=len), mode)
        version = find_version(segments, error, eci=eci, micro=False, is_sa=True)
    sa_info = partial(_StructuredAppendInfo, total=len(chunks) - 1,
                      parity=sa_parity_data)
    return [_encode(one_item_segments(chunk, mode), error=error, version=version,
                    mask=mask, eci=eci, boost_error=boost_error,
                    sa_info=sa_info(i)) for i, chunk in enumerate(chunks)]
501863
public static String pad(String rawString, int length, char padChar)
  {
    String padded = rawString;
    String padFiller = null;

    if (padded.length() == length)
    {
      return padded;
    }

    if (padded.length() < length)
    {
      //
      // Keep a zero string that is big enough to pad the
      // largest field that we have, then to pad each field
      // we just append this string to the field and then
      // substr to the desired size.
      //
      StringBuffer buff = new StringBuffer(length);

      for (int i = buff.length(); i < length; i++)
      {
        buff.append(padChar);
      }
      padFiller = buff.toString();

      padded = rawString + padFiller;
      return padded.substring(0, length);

    }
    else
    {
      return padded.substring(0, length);
    }
  }
870248
def removeRandomLenPadding(str, blocksize=AES_blocksize):
  ''
  pad_len = ord(str[-1]) # last byte contains number of padding bytes
  assert pad_len < blocksize, 'padding error' 
  assert pad_len < len(str), 'padding error'
    
  return str[:-pad_len]
219188
function ecc200encode(&$t, &$tl, $s, $sl, $e) {
        // start in ASCII encoding mode
        $enc = 'a';
        $tp = 0;
        $sp = 0;
        $p = 0;
        $v = 0;
        $w = 0;

        $oldErrorReporting = error_reporting(0);

        //does not work, but is said to be optional, doesn't work in the JS code either because of a typo
        //        if ($e['encodingLength'] < $sl)
        //        {
        //            die("Encoding string too short");
        //            return 0;
        //        }

        // do the encoding
        while ($sp < $sl && $tp < $tl) {
            // suggest new encoding
            $newenc = $enc;
            if ($tl - $tp <= 1 && ($enc == 'c' || $enc == 't') || $tl - $tp <= 2 && $enc == 'x')
                // auto revert to ASCII
                $enc = 'a';
            //$this->debug("encoding: " + e.encoding);
            //$this->debug("encoding[sp]: " + e.encoding[sp]);
            $newenc = strtolower($e['encoding'][$sp]);
            switch ($newenc) {
                // encode character
                case 'c':
                    // C40
                case 't':
                    // Text
                case 'x': {
                    // X12
                    $out = array_fill(0, 6, 0);
                    $p = 0;
                    $s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_\232";
                    $s3 = "";
                    if ($newenc == 'c') {
                        $en = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                        $s3 = "`abcdefghijklmnopqrstuvwxyz{|}~\177";
                    }
                    if ($newenc == 't') {
                        $en = " 0123456789abcdefghijklmnopqrstuvwxyz";
                        $s3 = "`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\177";
                    }
                    if ($newenc == 'x')
                        $en = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\r*>";
                    do {
                        $c = $s{$sp++};
                        if ($c & 0x80) {
                            if ($newenc == 'x') {
                                die("Cannot encode char in X12: " . $c);
                                return 0;
                            }
                            $c = $c & 0x7f;
                            $out[$p++] = 1;
                            $out[$p++] = 30;
                        }
                        $w = strpos($en, $c);
                        if ($w !== false)
                            $out[$p++] = ($w + 3) % 40;
                        else {
                            if ($newenc == 'x') {
                                die("Cannot encode char in X12: " . $c);
                                return 0;
                            }
                            if (ord($c) < 32) {
                                // shift 1 XXX
                                $out[$p++] = 0;
                                $out[$p++] = $c;
                            } else {
                                $w = strpos($s2, $c);
                                if ($w !== false) {
                                    // shift 2
                                    $out[$p++] = 1;
                                    $out[$p++] = $w;
                                } else {
                                    $w = strpos($s3, $c);
                                    if ($w !== false) {
                                        $out[$p++] = 2;
                                        $out[$p++] = $w;
                                    } else {
                                        die("Should not happen. Could not encode: " . $c);
                                        return 0;
                                    }
                                }
                            }
                        }
                        if ($p == 2 && $tp + 2 == $tl && $sp == $sl)
                            // shift 1 $pad at end
                            $out[$p++] = 0;
                        while ($p >= 3) {
                            $v = $out[0] * 1600 + $out[1] * 40 + $out[2] + 1;
                            if ($enc != $newenc) {
                                if ($enc == 'c' || $enc == 't' || $enc == 'x')
                                    // escape C40/text/X12
                                    $t[$tp++] = 254;
                                elseif ($enc == 'x')
                                    // escape EDIFACT
                                    $t[$tp++] = 0x7C;
                                if ($newenc == 'c')
                                    $t[$tp++] = 230;
                                if ($newenc == 't')
                                    $t[$tp++] = 239;
                                if ($newenc == 'x')
                                    $t[$tp++] = 238;
                                $enc = $newenc;
                            }
                            $t[$tp++] = ($v >> 8);
                            $t[$tp++] = ($v & 0xFF);
                            $p -= 3;
                            $out[0] = $out[3];
                            $out[1] = $out[4];
                            $out[2] = $out[5];
                        }
                    } while ($p && $sp < $sl);
                }
                break;
                case 'e': {
                    // EDIFACT
                    $out = array_fill(0, 4, 0);
                    $p = 0;
                    if ($enc != $newenc) {
                        // can only be from C40/Text/X12
                        $t[$tp++] = 254;
                        $enc = 'a';
                    }
                    while ($sp < $sl && strtolower($e['encoding'][$sp]) == 'e' && $p < 4)
                        $out[$p++] = ord($s{$sp++});
                    if ($p < 4) {
                        $out[$p++] = 0x1F;
                        $enc = 'a';
                    }
                    // termination
                    $t[$tp] = (($s{0} & 0x3F) << 2);
                    $ttp = $tp++;
                    $t[$ttp] = $t[$ttp] | (($s{1} & 0x30) >> 4);
                    $t[$tp] = (($s{1} & 0x0F) << 4);
                    if ($p == 2)
                        $tp++;
                    else {
                        $ttp = $tp++;
                        $t[$ttp] = $t[$ttp] | (($s[2] & 0x3C) >> 2);
                        $t[$tp] = (($s{2} & 0x03) << 6);
                        $ttp = $tp++;
                        $t[$ttp] = $t[$ttp] | ($s{3} & 0x3F);
                    }
                }
                break;
                case 'a':
                    // ASCII
                    if ($enc != $newenc) {
                        if ($enc == 'c' || $enc == 't' || $enc == 'x')
                            // escape C40/text/X12
                            $t[$tp++] = 254;
                        else
                            // escape EDIFACT
                            $t[$tp++] = 0x7C;
                    }
                    $enc = 'a';
                    if ($sl - $sp >= 2 && $this->isDigit($s{$sp}) && $this->isDigit($s{$sp + 1})) {
                        $t[$tp++] = (ord($s{$sp}) - ord('0')) * 10 + ord($s{$sp + 1}) - ord('0') + 130;
                        $sp += 2;
                    } elseif (ord($s{$sp}) > 127) {
                        $t[$tp++] = 235;
                        $t[$tp++] = ord($s{$sp++}) - 127;
                    } else
                        $t[$tp++] = ord($s{$sp++}) + 1;
                    break;
                case 'b': {
                    // Binary
                    // how much to encode
                    $l = 0;
                    if ($encoding) {
                        for ($p = $sp; $p < $sl && strtolower($e['encoding'][$p]) == 'b'; $p++)
                            $l++;
                    }
                    // base256
                    $t[$tp++] = 231;
                    if ($l < 250)
                        $t[$tp++] = $l;
                    else {
                        $t[$tp++] = 249 + floor(l / 250);
                        $t[$tp++] = ($l % 250);
                    }
                    while ($l-- && $tp < $tl) {
                        // see annex H
                        $t[$tp] = ord($s{$sp++}) + ((($tp + 1) * 149) % 255) + 1;
                        $tp++;
                    }
                    // reverse to ASCII at end
                    $enc = 'a';
                }
                break;
                default:
                    die("Unknown encoding: " . $newenc);
                    // failed
                    return 0;
            }
        }
        if ($tp < $tl && $enc != 'a') {
            if ($enc == 'c' || $enc == 'x' || $enc == 't')
                // escape X12/C40/Text
                $t[$tp++] = 254;
            else
                // escape EDIFACT
                $t[$tp++] = 0x7C;
        }
        if ($tp < $tl)
            // $pad
            $t[$tp++] = 129;
        while ($tp < $tl) {
            // more $padding
            // see Annex H
            $v = 129 + ((($tp + 1) * 149) % 253) + 1;
            if ($v > 254)
                $v -= 254;
            $t[$tp++] = $v;
        }

        error_reporting($oldErrorReporting);

        if ($tp > $tl || $sp < $sl) // did not fit
            return 0;
        // OK
        return $tp;
    }
874310
@SuppressWarnings({"NarrowingCompoundAssignment", "ImplicitNumericConversion"})
    public static void encodeNullsAsBits(SliceOutput sliceOutput, Block block)
    {
        boolean mayHaveNull = block.mayHaveNull();
        sliceOutput.writeBoolean(mayHaveNull);
        if (!mayHaveNull) {
            return;
        }

        int positionCount = block.getPositionCount();
        for (int position = 0; position < (positionCount & ~0b111); position += 8) {
            byte value = 0;
            value |= block.isNull(position) ? 0b1000_0000 : 0;
            value |= block.isNull(position + 1) ? 0b0100_0000 : 0;
            value |= block.isNull(position + 2) ? 0b0010_0000 : 0;
            value |= block.isNull(position + 3) ? 0b0001_0000 : 0;
            value |= block.isNull(position + 4) ? 0b0000_1000 : 0;
            value |= block.isNull(position + 5) ? 0b0000_0100 : 0;
            value |= block.isNull(position + 6) ? 0b0000_0010 : 0;
            value |= block.isNull(position + 7) ? 0b0000_0001 : 0;
            sliceOutput.appendByte(value);
        }

        // write last null bits
        if ((positionCount & 0b111) > 0) {
            byte value = 0;
            int mask = 0b1000_0000;
            for (int position = positionCount & ~0b111; position < positionCount; position++) {
                value |= block.isNull(position) ? mask : 0;
                mask >>>= 1;
            }
            sliceOutput.appendByte(value);
        }
    }
847094
private static byte[] encodeEnternal(byte[] d)
    {
        if (d == null) return null;
        byte data[] = new byte[d.length+2];
        System.arraycopy(d, 0, data, 0, d.length);
        byte dest[] = new byte[(data.length/3)*4];

        // 3-byte to 4-byte conversion
        for (int sidx = 0, didx=0; sidx < d.length; sidx += 3, didx += 4)
        {
            dest[didx]   = (byte) ((data[sidx] >>> 2) & 077);
            dest[didx+1] = (byte) ((data[sidx+1] >>> 4) & 017 |
                    (data[sidx] << 4) & 077);
            dest[didx+2] = (byte) ((data[sidx+2] >>> 6) & 003 |
                    (data[sidx+1] << 2) & 077);
            dest[didx+3] = (byte) (data[sidx+2] & 077);
        }

        // 0-63 to ascii printable conversion
        for (int idx = 0; idx <dest.length; idx++)
        {
            if (dest[idx] < 26)     dest[idx] = (byte)(dest[idx] + 'A');
            else if (dest[idx] < 52)  dest[idx] = (byte)(dest[idx] + 'a' - 26);
            else if (dest[idx] < 62)  dest[idx] = (byte)(dest[idx] + '0' - 52);
            else if (dest[idx] < 63)  dest[idx] = (byte)'+';
            else            dest[idx] = (byte)'/';
        }

        // add padding
        for (int idx = dest.length-1; idx > (d.length*4)/3; idx--)
        {
            dest[idx] = (byte)'=';
        }
        return dest;
    }
934444
def left_zero_pad(s, blocksize):
    
    if blocksize > 0 and len(s) % blocksize:
        s = (blocksize - len(s) % blocksize) * b('\000') + s
    return s
1221963
public static String rpad(String base, int len, String pad) {
		if (len < 0 || "".equals(pad)) {
			return null;
		} else if (len == 0) {
			return "";
		}

		char[] data = new char[len];
		char[] baseChars = base.toCharArray();
		char[] padChars = pad.toCharArray();

		int pos = 0;

		// copy the base
		while (pos < base.length() && pos < len) {
			data[pos] = baseChars[pos];
			pos += 1;
		}

		// copy the padding
		while (pos < len) {
			int i = 0;
			while (i < pad.length() && i < len - pos) {
				data[pos + i] = padChars[i];
				i += 1;
			}
			pos += pad.length();
		}

		return new String(data);
	}
474118
private void handleEntityDecl(boolean suppressPEDecl)
        throws XMLStreamException
    {
        /* Hmmh. It seems that PE reference are actually accepted
         * even here... which makes distinguishing definition from
         * reference bit challenging.
         */
        char c = dtdNextFromCurr();
        boolean gotSeparator = false;
        boolean isParam = false;

        while (true) {
            if (c == '%') { // reference?
                // note: end-of-block acceptable, same as space
                char d = dtdNextIfAvailable();
                if (d == CHAR_NULL || isSpaceChar(d)) { // ok, PE declaration
                    isParam = true;
                    if (d == '\n' || c == '\r') {
                        skipCRLF(d);
                    }
                    break;
                }
                // Reference?
                if (!isNameStartChar(d)) {
                    throwDTDUnexpectedChar(d, "; expected a space (for PE declaration) or PE reference name");
                }
                --mInputPtr; // need to push the first char back, then
                gotSeparator = true;
                expandPE();
                // need the next char, from the new scope... or if it gets closed, this one
                c = dtdNextChar();
            } else if (!isSpaceChar(c)) { // non-PE entity?
                break;
            } else {
                gotSeparator = true;
                c = dtdNextFromCurr();
            }
        }

        if (!gotSeparator) {
            throwDTDUnexpectedChar(c, "; expected a space separating ENTITY keyword and entity name");
        }

        /* Ok; fair enough: now must have either '%', or a name start
         * character:
         */
        if (isParam) {
            /* PE definition: at this point we already know that there must
             * have been a space... just need to skip the rest, if any.
             * Also, can still get a PE to expand (name of a PE to define
             * from a PE reference)
             */
            c = skipDtdWs(true);
        }

        if (suppressPEDecl) { // only if mFlattenWriter != null
            if (!isParam) {
                mFlattenWriter.enableOutput(mInputPtr);
                mFlattenWriter.output("<!ENTITY ");
                mFlattenWriter.output(c);
            }
        }

        // Need a name char, then
        String id = readDTDName(c);

        /* Ok, event needs to know its exact starting point (opening '<'
         * char), let's get that info now (note: data has been preserved
         * earlier)
         */
        Location evtLoc = getStartLocation();
        EntityDecl ent;

        try {
            c = skipObligatoryDtdWs();
            if (c == '\'' || c == '"') { // internal entity
                /* Let's get the exact location of actual content, not the
                 * opening quote. To do that, need to 'peek' next char, then
                 * push it back:
                 */
                /*char foo =*/ dtdNextFromCurr();
                Location contentLoc = getLastCharLocation();
                --mInputPtr; // pushback
                char[] contents = parseEntityValue(id, contentLoc, c);
                try {
                	ent = new IntEntity(evtLoc, id, getSource(), contents, contentLoc);
                } catch (IOException e) {
                	throw new WstxIOException(e);
                }
            } else {
                if (!isNameStartChar(c)) {
                    throwDTDUnexpectedChar(c, "; expected either quoted value, or keyword 'PUBLIC' or 'SYSTEM'");
                }
                ent = handleExternalEntityDecl(mInput, isParam, id, c, evtLoc);
            }

            /* 05-Mar-2006, TSa: Need to know which entities came from the
             *    external subset; these can not be used if the xml document
             *    is declared as "standalone='yes'".
             */
            if (mIsExternal) {
                ent.markAsExternallyDeclared();
            }
        } finally {
            /* Ok; one way or the other, entity declaration contents have now
             * been read in.
             */
            if (suppressPEDecl && isParam) {
                mFlattenWriter.enableOutput(mInputPtr);
            }
        }

        // Ok, got it!
        HashMap<String,EntityDecl> m;
        if (isParam) {
            m = mParamEntities;
            if (m == null) {
                mParamEntities = m = new HashMap<String,EntityDecl>();
            }
        } else {
            m = mGeneralEntities;
            if (m == null) {
                /* Let's try to get insert-ordered Map, to be able to
                 * report redefinition problems when validating subset
                 * compatibility
                 */
                mGeneralEntities = m = new LinkedHashMap<String,EntityDecl>();
            }
        }

        // First definition sticks...
        Object old;
        if (m.size() > 0 && (old = m.get(id)) != null) {
            // Application may want to know about the problem...
            XMLReporter rep = mConfig.getXMLReporter();
            if (rep != null) {
                EntityDecl oldED = (EntityDecl) old;
                String str = " entity '"+id+"' defined more than once: first declaration at "
                    + oldED.getLocation();
                if (isParam) {
                    str = "Parameter" + str;
                } else {
                    str = "General" + str;
                }
                _reportWarning(rep, ErrorConsts.WT_ENT_DECL, str, evtLoc);
            }
        } else {
            m.put(id, ent);
        }

        // And finally, let's notify listener, if we have one...
        if (mEventListener != null) {
            if (ent.isParsed()) { // Parsed GE or PE
            } else { // unparsed GE
            	final URL src;
            	try {
            		src = mInput.getSource();
                } catch (IOException e) {
                	throw new WstxIOException(e);
                }
                mEventListener.dtdUnparsedEntityDecl(id, ent.getPublicId(), ent.getSystemId(), ent.getNotationName(), src);
            }
        }
    }