Skip to content

Instantly share code, notes, and snippets.

@aarnchng
Created August 23, 2011 09:45
Show Gist options
  • Select an option

  • Save aarnchng/1164756 to your computer and use it in GitHub Desktop.

Select an option

Save aarnchng/1164756 to your computer and use it in GitHub Desktop.

Revisions

  1. Aaron Yong created this gist Aug 23, 2011.
    92 changes: 92 additions & 0 deletions DataReader.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,92 @@
    package references;

    import java.io.IOException;
    import java.io.InputStream;

    import android.util.Log;

    abstract class DataReader {

    public static final int INVALID_DATA = -1;
    private InputStream dis = null;

    protected DataReader(InputStream is) {
    dis = is;
    }

    public abstract boolean read();

    protected float readFloat() {
    int value = readInt();
    if (value != INVALID_DATA) {
    return Float.intBitsToFloat(value);
    }
    return INVALID_DATA;
    }

    protected int readInt() {
    byte[] bytes = readBytes(4);
    if (bytes != null) {
    int value = 0;
    value += (bytes[3] & 0x000000FF) << 24;
    value += (bytes[2] & 0x000000FF) << 16;
    value += (bytes[1] & 0x000000FF) << 8;
    value += (bytes[0] & 0x000000FF);
    return value;
    }
    return INVALID_DATA;
    }

    protected double readDouble() {
    long value = readLong();
    if (value != INVALID_DATA) {
    return Double.longBitsToDouble(value);
    }
    return INVALID_DATA;
    }

    protected long readLong() {
    byte[] bytes = readBytes(8);
    if (bytes != null) {
    long value = 0;
    value += (long) (bytes[7] & 0x000000FF) << 56;
    value += (long) (bytes[6] & 0x000000FF) << 48;
    value += (long) (bytes[5] & 0x000000FF) << 40;
    value += (long) (bytes[4] & 0x000000FF) << 32;
    value += (bytes[3] & 0x000000FF) << 24;
    value += (bytes[2] & 0x000000FF) << 16;
    value += (bytes[1] & 0x000000FF) << 8;
    value += (bytes[0] & 0x000000FF);
    return value;
    }
    return INVALID_DATA;
    }

    protected void skipBytes(int length) {
    try {
    int count = (int) dis.skip(length);
    if (count != length) {
    Log.i("Incorrect Data Size (Intended:Actual): ",
    String.valueOf(length) + ":" + String.valueOf(count));
    }
    } catch (IOException ex) {
    Log.w("[email protected]()", ex);
    }
    }

    protected void readBytes(int length) {
    byte[] bytes = new byte[length];
    try {
    int count = dis.read(bytes, 0, length);
    if (count != length) {
    Log.i("Incorrect Data Size (Intended:Actual): ",
    String.valueOf(length) + ":" + String.valueOf(count));
    return null;
    }
    return bytes;
    } catch (IOException ex) {
    Log.w("[email protected]()", ex);
    }
    return null;
    }
    }