-
-
Save rbrovko/9ee39dd387dde4e0eb8ddb81c292d9f4 to your computer and use it in GitHub Desktop.
DataReader.java - Convert Byte Array To Integer/Long/Float/Double
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment