JAVA JDBC驅動程序PostgreSQL:解析編號為BYTEA對象的數字

[英]JAVA JDBC Driver PostgreSQL: Parse numbers encoded as BYTEA object


I have relation where for each record there is BYTEA column (UTF-8) encoding 3 numbers in the following order:

我有關系,每個記錄有BYTEA列(UTF-8)按以下順序編碼3個數字:

bytes 0-1: number 1

字節0-1:數字1

bytes 2-3: number 2

字節2-3:數字2

bytes 4-6: number 3

字節4-6:數字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,

2 个解决方案

#1


2  

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可能更容易:

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.

ByteBuffer默認為BIG_ENDIAN。

#2


0  

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 []:

    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);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/05/28/72efec33fd43fd4f1bf9c5f78e8faf11.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com