簡體   English   中英

使用Byte數組和BitSet類從JAVA的SQL表中檢索二進制數據

[英]Retrieving binary data from SQL table in JAVA with Byte array and BitSet class

表格結構-列X(二進制(15),空)

X列中的值-000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

即15x8 = 120位

SQL查詢

Select X from tablename;

檢索值的Java代碼部分: barraybyte[]bitsnew BitSet()

barray = resultset.getBytes("X");

if(barray != null) {
   for (int i = 0; i < barray.length * 8; i++) {
      if ((barray[barray.length-i/8-1]&(1<<(i%8))) > 0) {
         bits.set(i);
      }
   }
}

問題:第二個if語句返回假值(不確定y?),因此未填充bits對象。 請提出解決方案。

我認為您的錯誤超出了您發布的代碼范圍,因為我將其包裝在此程序中,並且可以在這里運行:

package de.fencing_game.paul.examples;

import java.util.BitSet;

/**
 * Test class for http://stackoverflow.com/questions/5391097/retrieving-binary-data-from-sql-table-in-java-with-byte-array-and-bitset-class.
 */
public class BitSetByteArrayTest {


    public static void main(String[] params) {

        byte[] barray= new byte[]{ 0x01, 0x02, 0x04, 0x08,
                                   0x10, 0x20, 0x40, (byte)0x80,
                                   };
        BitSet bits = new BitSet();

        if(barray!=null){
            for (int i=0; i<barray.length*8; i++) {
                if ((barray[barray.length-i/8-1]&(1<<(i%8))) > 0) {
                    bits.set(i);
                }
            }
        }
        System.out.println(bits);
    }
}

它也可以與您的輸入

    byte[] barray = { 0,    0, 0, 0, 0,
                      0x20, 0, 0, 0, 0,
                      0,    0, 0, 0, 0};

而不是示例數組,然后顯示{77}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM