Skip to content

Instantly share code, notes, and snippets.

@aarnchng
Created August 23, 2011 09:45
Show Gist options
  • Save aarnchng/1164756 to your computer and use it in GitHub Desktop.
Save aarnchng/1164756 to your computer and use it in GitHub Desktop.
DataReader.java - Convert Byte Array To Integer/Long/Float/Double
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;
}
}
@jamescurtis
Copy link

Is the return type of the readBytes wrong? Its returns a bytes array on line 86, yet the return type is void.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment