我有关系,每条记录都有BYTEA列(UTF-8)按以下顺序编码3个数字:
字节0-1:数字1
字节2-3:数字2
字节4-6:数字3
如何将二进制数据解析为可读数字?
目前我有这个并且不知道如何继续:
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
}
谢谢,
答案 0 :(得分:2)
这取决于数字的存储方式 它们是二进制的吗? 他们是signed吗? 它们是大还是小endian?
假设前两个是,你可以使用位操作,例如
// Little-endian
short num1 = (short) ((data[0] & 0xFF) | (data[1] & 0xFF) << 8);
// Big-endian
short num1 = (short) ((data[0] & 0xFF) << 8 | (data[1] & 0xFF));
但它可能更容易使用ByteBuffer
:
ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
short num1 = buf.getShort();
short num2 = buf.getShort();
short num3 = buf.getShort();
ByteBuffer
默认为BIG_ENDIAN
。
答案 1 :(得分:0)
你可以试试这个:
For String:
String tatto = "my tatto"; //for example
byte[] array = tatto.getBytes(); // Or any bytes
String s = new String(array);
System.out.println(s);
对于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);