TsigumEnes
TsigumEnes

Reputation: 131

Convert List<Boolean> to byte [ ] array

I have a list of booleans which I want to convert Byte [] arrays.I try to convert List to byte[] arrays but I have a mistake.This is my code

 List<Boolean> list = model.getBooleanData();
               boolean[] inputSleep = new boolean[list.size()];

               byte[] toReturn = new byte[inputSleep.length / 8];
               for (int entry = 0; entry < toReturn.length; entry++) {
                   for (int bit = 0; bit < 8; bit++) {
                       if (inputSleep[entry * 8 + bit]) {
                           toReturn[entry] |= (128 >> bit);
                       }
                   }
               }

I get all Booleans and checked but I try to this all Booleans false.Thanks your helps.How can I correctly convert List to byte[] arrays?

Upvotes: 2

Views: 751

Answers (1)

TsigumEnes
TsigumEnes

Reputation: 131

Yeap thank you guys I solved the problem. This is the right code. Maybe this solution needs someone)

 List<Boolean> list = model.getBooleanData();
               Boolean[] inputSleep = new Boolean[list.size()];
               inputSleep = list.toArray(inputSleep);


               byte[] toReturn = new byte[inputSleep.length / 8];
               for (int entry = 0; entry < toReturn.length; entry++) {
                   for (int bit = 0; bit < 8; bit++) {
                       if (inputSleep[entry * 8 + bit]) {
                           toReturn[entry] |= (128 >> bit);
                       }
                   }
               }

Upvotes: 2

Related Questions