Reputation: 3955
I have relation where for each record there is BYTEA column (UTF-8) encoding 3 numbers in the following order:
bytes 0-1: number 1
bytes 2-3: number 2
bytes 4-6: number 3
How can I parse the binary data to readable numbers?
Currently I have this and don't know how to continue:
Class.forName(dbDriver);
Connection connection = DriverManager.getConnection(dbUrl, dbUser, dbPass);
Statement st = connection.createStatement();
String query = "SELECT ...";
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
byte[] data = rs.getBytes(1);
//TODO Parse
}
Thanks,
Upvotes: 1
Views: 585
Reputation: 2224
Can you try this :
For String :
String tatto = "my tatto"; //for example
byte[] array = tatto.getBytes(); // Or any bytes
String s = new String(array);
System.out.println(s);
For byte[] :
byte[] data = new byte[]{ 1, 16, 84, 2, 101, 110, 83, 111};
long val = 0;
for (int i = 0; i < data.length; i++)
{
val = (val << 8) + (data[i] & 0xff);
}
System.out.println(val);
Upvotes: 0
Reputation: 159250
That depends on how the numbers are stored.
Are they binary?
Are they signed?
Are they big or little endian?
Assuming yes to the first two, you can use bit-manipulation, e.g.
// Little-endian
short num1 = (short) ((data[0] & 0xFF) | (data[1] & 0xFF) << 8);
// Big-endian
short num1 = (short) ((data[0] & 0xFF) << 8 | (data[1] & 0xFF));
But it's probably easier to use ByteBuffer
:
ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
short num1 = buf.getShort();
short num2 = buf.getShort();
short num3 = buf.getShort();
ByteBuffer
is BIG_ENDIAN
by default.
Upvotes: 2