Code example for DataOutput

Methods: writeByte, writeInt, writeLong, writeShort

0
   * @throws IOException 
   */ 
  @SuppressWarnings("fallthrough") 
  public static void writeVLong(DataOutput out, long n) throws IOException {
    if ((n < 128) && (n >= -32)) {
      out.writeByte((int) n);
      return; 
    } 
 
    long un = (n < 0) ? ~n : n;
    // how many bytes do we need to represent the number with sign bit? 
    int len = (Long.SIZE - Long.numberOfLeadingZeros(un)) / 8 + 1;
    int firstByte = (int) (n >> ((len - 1) * 8));
    switch (len) {
      case 1: 
        // fall it through to firstByte==-1, len=2. 
        firstByte >>= 8;
      case 2: 
        if ((firstByte < 20) && (firstByte >= -20)) {
          out.writeByte(firstByte - 52);
          out.writeByte((int) n);
          return; 
        } 
        // fall it through to firstByte==0/-1, len=3. 
        firstByte >>= 8;
      case 3: 
        if ((firstByte < 16) && (firstByte >= -16)) {
          out.writeByte(firstByte - 88);
          out.writeShort((int) n);
          return; 
        } 
        // fall it through to firstByte==0/-1, len=4. 
        firstByte >>= 8;
      case 4: 
        if ((firstByte < 8) && (firstByte >= -8)) {
          out.writeByte(firstByte - 112);
          out.writeShort(((int) n) >>> 8);
          out.writeByte((int) n);
          return; 
        } 
        out.writeByte(len - 129);
        out.writeInt((int) n);
        return; 
      case 5: 
        out.writeByte(len - 129);
        out.writeInt((int) (n >>> 8));
        out.writeByte((int) n);
        return; 
      case 6: 
        out.writeByte(len - 129);
        out.writeInt((int) (n >>> 16));
        out.writeShort((int) n);
        return; 
      case 7: 
        out.writeByte(len - 129);
        out.writeInt((int) (n >>> 24));
        out.writeShort((int) (n >>> 8));
        out.writeByte((int) n);
        return; 
      case 8: 
        out.writeByte(len - 129);
        out.writeLong(n);
        return; 
      default: 
        throw new RuntimeException("Internel error");
    } 
  }