Table Structure - Column X(Binary (15),null)
Value in Column X - 000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000
i.e 15x8=120 bits
SQL query
Select X from tablename;
Java Code part 开发者_运维百科for retrieving value: barray
is byte[]
and bits
is new 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);
}
}
}
Problem: The 2nd if statement is returning false value(not sure y?) thus the bits object is not getting populated. Please suggest a solution.
I think your mistake is outside of the code you posted, as I wrapped it in this program, and it works here:
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);
}
}
It works also with your input
byte[] barray = { 0, 0, 0, 0, 0,
0x20, 0, 0, 0, 0,
0, 0, 0, 0, 0};
instead of the sample array, showing {77}
then.
精彩评论