Recuperar dados binários da tabela SQL em JAVA com matriz de bytes e classe BitSet
-
28-10-2019 - |
Pergunta
Estrutura da tabela - Coluna X (binário (15), nulo)
Valor na coluna X - 0000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000
ou seja, 15x8= 120 bits
Consulta SQL
Select X from tablename;
Parte do código Java para recuperar o valor: barray
é byte[]
e bits
é 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);
}
}
}
Problema: a segunda instrução if está retornando um valor falso (não tem certeza de y?), portanto, o objeto de bits não está sendo populado.Por favor, sugira uma solução.
Solução
Acho que seu erro está fora do código que você postou, conforme envolvi neste programa, e funciona aqui:
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);
}
}
Também funciona com a sua entrada
byte[] barray = { 0, 0, 0, 0, 0,
0x20, 0, 0, 0, 0,
0, 0, 0, 0, 0};
em vez da matriz de amostra, mostrando {77}
então.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow