2

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.

3
  • Java code part: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); } } } Commented Mar 22, 2011 at 12:22
  • What bytes are you getting? Just print them out, to see if you're getting nonzero data out of the DB -- then you can figure out whether the problem is in the DB read or in the BitSet transcoding. Commented Mar 22, 2011 at 12:43
  • for the next time: you can format your source by putting 4 spaces before it, or using `` to wrap it inline. Commented Mar 22, 2011 at 13:01

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@JavaBits: What was the reason?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.