Decode an ASN.1 BIT STRING.

@param buf
the buffer containing the DER-encoded BIT STRING.
@return the bits in the BIT STRING
771789
public static BitSet decodeBitString(ByteBuffer buf) {
        DerId id = DerId.decode(buf);
        if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_BIT_STRING_TAG_NUM)
                && !id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.CONSTRUCTED, ASN1_BIT_STRING_TAG_NUM)) {
            throw new IllegalArgumentException("Expected BIT STRING identifier, received " + id);
        }
        int len = DerUtils.decodeLength(buf);
        if (buf.remaining() < len) {
            throw new IllegalArgumentException("Insufficient content for BIT STRING");
        }

        // If primitive encoding, then the initial octet is just used for padding
        if (id.getEncodingType() == DerId.EncodingType.PRIMITIVE) {
            buf.get();
            len--;
        }

        int nbits = len * 8;
        BitSet bits = new BitSet(nbits);
        for (int i = 0; i < len; i++) {
            short next = (short) (0xff & buf.get());
            int bitIndex = (i + 1) * 8 - 1;
            while (next != 0) {
                if ((next & 1) == 1) {
                    bits.set(bitIndex);
                }
                bitIndex--;
                next >>>= 1;
            }
        }
        return bits;
    }
528996
private static void decodeEdifactSegment(BitSource bits, StringBuilder result) {
    do {
      // If there is only two or less bytes left then it will be encoded as ASCII
      if (bits.available() <= 16) {
        return;
      }

      for (int i = 0; i < 4; i++) {
        int edifactValue = bits.readBits(6);

        // Check for the unlatch character
        if (edifactValue == 0x1F) {  // 011111
          // Read rest of byte, which should be 0, and stop
          int bitsLeft = 8 - bits.getBitOffset();
          if (bitsLeft != 8) {
            bits.readBits(bitsLeft);
          }
          return;
        }

        if ((edifactValue & 0x20) == 0) {  // no 1 in the leading (6th) bit
          edifactValue |= 0x40;  // Add a leading 01 to the 6 bit binary value
        }
        result.append((char) edifactValue);
      }
    } while (bits.available() > 0);
  }
1015472
public static DerId decodeIdAndLength(ByteBuffer buf) {
        DerId id = DerId.decode(buf);
        DerUtils.decodeLength(buf);
        return id;
    }
124530
def _decode_string(buf, pos):
    
    for i in range(pos, len(buf)):
        if buf[i:i+1] == _compat_bytes('\x00'):
            try:
                return (buf[pos:i].decode(_CHARSET), i+1)
            # Uncomment the following two lines for detailled information
            #except UnicodeDecodeError as ude:
            #   raise MinusconfError(str(ude))
            except UnicodeDecodeError:
                raise MinusconfError('Not a valid ' + _CHARSET + ' string: ' + repr(buf[pos:i]))

    raise MinusconfError("Premature end of string (Forgot trailing \\0?), buf=" + repr(buf))
48162
function decode(buf) {
  let off = 0;
  var i;

  // unpack meta
  const meta = buf[(off += 1)];
  // const VERSION = meta >> 4;
  const argv = meta & 0xf;
  const args = new Array(argv);

  // unpack args
  for (i = 0; i < argv; i += 1) {
    const len = buf.readUInt32BE(off);
    off += 4;

    args[i] = buf.slice(off, (off += len));
  }

  return args;
}
99920
public static String readString(ByteBuffer buf) {
        if(buf.get() == 0)
            return null;
        int len=readInt(buf);
        if(buf.isDirect()) {
            byte[] bytes=new byte[len];
            buf.get(bytes);
            return new String(bytes);
        }
        else {
            byte[] bytes=buf.array();
            return new String(bytes, buf.arrayOffset() + buf.position(), len);
        }
    }
1208330
public static byte[] decode(String s) {
        int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
        byte[] buffer = new byte[s.length() * 3 / 4 - delta];
        int mask = 0xFF;
        int index = 0;
        for (int i = 0; i < s.length(); i += 4) {
            int c0 = toInt[s.charAt( i )];
            int c1 = toInt[s.charAt( i + 1)];
            buffer[index++] = (byte)(((c0 << 2) | (c1 >> 4)) & mask);
            if (index >= buffer.length) {
                return buffer;
            }
            int c2 = toInt[s.charAt( i + 2)];
            buffer[index++] = (byte)(((c1 << 4) | (c2 >> 2)) & mask);
            if (index >= buffer.length) {
                return buffer;
            }
            int c3 = toInt[s.charAt( i + 3 )];
            buffer[index++] = (byte)(((c2 << 6) | c3) & mask);
        }
        return buffer;
    }
653645
public static void putString(IoBuffer buf, String string) {
        final byte[] encoded = encodeString(string);
        if (encoded.length < AMF.LONG_STRING_LENGTH) {
            // write unsigned short
            buf.put((byte) ((encoded.length >> 8) & 0xff));
            buf.put((byte) (encoded.length & 0xff));
        } else {
            buf.putInt(encoded.length);
        }
        buf.put(encoded);
    }
616524
private static byte[] decodeBytes(byte[] pInBytes) {
        byte[] decodabet = DECODABET;

        int    len34   = pInBytes.length * 3 / 4;       // Estimate on array size
        byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
        int    outBuffPosn = 0;             // Keep track of where we're writing

        byte[] b4        = new byte[4];     // Four byte buffer from source, eliminating white space
        int    b4Posn    = 0;               // Keep track of four byte input buffer
        int    i         = 0;               // Source array counter
        byte   sbiCrop   = 0;               // Low seven bits (ASCII) of input
        byte   sbiDecode = 0;               // Special value from DECODABET

        for( i = 0; i < 0 + pInBytes.length; i++ ) {  // Loop through source

            sbiCrop = (byte)(pInBytes[i] & 0x7f); // Only the low seven bits
            sbiDecode = decodabet[ sbiCrop ];   // Special value

            // White space, Equals sign, or legit Base64 character
            // Note the values such as -5 and -9 in the
            // DECODABETs at the top of the file.
            if( sbiDecode >= WHITE_SPACE_ENC )  {
                if( sbiDecode >= EQUALS_SIGN_ENC ) {
                    b4[ b4Posn++ ] = sbiCrop;           // Save non-whitespace
                    if( b4Posn > 3 ) {                  // Time to decode?
                        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn);
                        b4Posn = 0;

                        // If that was the equals sign, break out of 'for' loop
                        if( sbiCrop == EQUALS_SIGN ) {
                            break;
                        }
                    }
                }
            }
            else {
                // There's a bad input character in the Base64 stream.
                throw new IllegalArgumentException(String.format(
                        "Bad Base64 input character '%d' in array position %d", pInBytes[i], i ) );
            }
        }

        byte[] out = new byte[ outBuffPosn ];
        System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
        return out;
    }
1101819
private static int decodeOctets(int i, ByteBuffer bb, StringBuilder sb) {
        // If there is only one octet and is an ASCII character
        if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {
            // Octet can be appended directly
            sb.append((char) bb.get(0));
            return i + 2;
        } else {
            //
            CharBuffer cb = UTF_8_CHARSET.decode(bb);
            sb.append(cb.toString());
            return i + bb.limit() * 3 - 1;
        }
    }
179398
public static String decode(String encoded) {
        // speedily leave if we're not needed
        if (encoded == null)
            return null;
        if (encoded.indexOf('%') == -1 && encoded.indexOf('+') == -1)
            return encoded;

        //allocate the buffer - use byte[] to avoid calls to new.
        byte holdbuffer[] = new byte[encoded.length()];

        char holdchar;
        int bufcount = 0;

        for (int count = 0; count < encoded.length(); count++) {
            char cur = encoded.charAt(count);
            if (cur == '%') {
                holdbuffer[bufcount++] = (byte) Integer.parseInt(encoded.substring(count + 1, count + 3), 16);
                if (count + 2 >= encoded.length())
                    count = encoded.length();
                else
                    count += 2;
            }
            else if (cur == '+') {
                holdbuffer[bufcount++] = (byte) ' ';
            }
            else {
                holdbuffer[bufcount++] = (byte) cur;
            }
        }
        // REVISIT -- remedy for Deprecated warning.
        //return new String(holdbuffer,0,0,bufcount);
        return new String(holdbuffer, 0, bufcount);
    }
1260417
static public Object decodeVarbinary(final ByteBuffer bb) {
        final int length = bb.getInt();
        final byte[] data = new byte[length];
        bb.get(data);
        return data;
    }
197254
public int read(byte []buf, int offset, int length) throws IOException
  {
    try {
      return readInt(buf, offset, length);
    } catch (IOException e) {
      _isKeepalive = false;
      throw e;
    } catch (RuntimeException e) {
      _isKeepalive = false;
      throw e;
    }
  }
122141
@Override
  public String decodeUtf8(ByteBuffer buffer, int offset, int length)
      throws IllegalArgumentException {
    if (buffer.hasArray()) {
      return decodeUtf8Array(buffer.array(), buffer.arrayOffset() + offset, length);
    } else {
      return decodeUtf8Buffer(buffer, offset, length);
    }
  }
378791
void encode(ChannelBuffer buf) {
        buf.writeByte('*');
        writeInt(buf, 1 + (args != null ? args.count() : 0));
        buf.writeBytes(CRLF);
        buf.writeByte('$');
        writeInt(buf, type.bytes.length);
        buf.writeBytes(CRLF);
        buf.writeBytes(type.bytes);
        buf.writeBytes(CRLF);
        if (args != null) {
            buf.writeBytes(args.buffer());
        }
    }
1337441
public static ByteBuffer slice(ByteBuffer buf, int off, int len)
	{
		ByteBuffer localBuf=buf.duplicate();	// so we don't mess up the position,etc
		logger.debug("off={} len={}", off, len);
		localBuf.position(off);
		localBuf.limit(off+len);
		logger.debug("pre-slice: localBuf.position()={} localBuf.limit()={}", localBuf.position(), localBuf.limit());
		localBuf = localBuf.slice();
		logger.debug("post-slice: localBuf.position()={} localBuf.limit()={}", localBuf.position(), localBuf.limit());
		return localBuf;
	}
1177192
private int read(ByteBuffer buf)
    {
        int nbytes;
        try {
            nbytes = fd.read(buf);
            if (nbytes == -1) {
                errno.set(ZError.ENOTCONN);
            }
            else if (nbytes == 0) {
                if (!fd.isBlocking()) {
                    //  If not a single byte can be read from the socket in non-blocking mode
                    //  we'll get an error (this may happen during the speculative read).

                    //  Several errors are OK. When speculative read is being done we may not
                    //  be able to read a single byte from the socket. Also, SIGSTOP issued
                    //  by a debugging tool can result in EINTR error.
                    errno.set(ZError.EAGAIN);
                    nbytes = -1;
                }
            }
        }
        catch (IOException e) {
            errno.set(ZError.ENOTCONN);
            nbytes = -1;
        }

        return nbytes;
    }