How to convert byte to Boolean[8] and convert back?

Asked

Viewed 227 times

7

I need to record some booleans in a File, and then retrieve them. I can record and read one or more bytes with the Classes java.io.FileInputStream and java.io.FileOutputStream, so I need to convert 1 byte to an array of 8 booleans, and, the conversion of an array of 8 booleans to 1 byte, so:

public static boolean[] byteToBooleanArray(byte b) {
    boolean[] array = new boolean[8];
    //O que colocar aqui?
    return array;
}

public static byte booleanArrayToByte(boolean[] array) {
    if (array.length != 8) throw new IllegalArgumentException();
    byte b;
    //O que colocar aqui?
    return b;
}

Note: I wish I didn’t have to download a library.

  • Interesting problem yours. + 1

2 answers

6


I believe that there will be various ways of doing this.
What I can think of now is:

  • Use expression (b & (1 << i)) != 0 to check whether the bit in position i byte is "set" and store the result at its position in the array.

    public static boolean[] byteToBooleanArray(byte b) {
        boolean[] array = new boolean[8];
        for (int i=0; i<8 ;i++){
            array[i] = (b & (1 << i)) != 0;
        }
        return array;
    }
    
  • Use expression b |= 1 << i for "setar", in byte, the bit in the position that corresponds to the position i array, if its value is true.

    public static byte booleanArrayToByte(boolean[] array) {
        if (array.length != 8) throw new IllegalArgumentException();
        byte b = 0;
        for (int i = 0; i < 8; i++) {
            if (array[i]) {
                b |= 1 << i;
            }
        }
        return b;
    }
    
  • Thank you @ramaral, I tested your code against others I found on Soen, to see if it gave the same exit for the same entry. I found that your "byteToBooleanArray()" gives the same result as the fixed algorithm here. But the most incredible, is that your "booleanArrayToByte()" did not give the same result of the answer accepted (with 5 votes!) here; but it’s almost the same as the other reply

  • by my tests is your "booleanArrayToByte()" which is right. thank you very much!

  • 1

    What happens in that reply is that the values are reversed: the position 0 of the array corresponds to bit 8. One way to test is if from a given value, after using both methods, it reaches the same value.

  • @Douglas I was working out a response based on that answer as well, until I realized what the ramaral explained above, that it reverses the array of booleans when converting. Not to mention that it fixes the size of an array received at 8, in your case it’s not even a problem, but it gets kind of strange, since the method doesn’t know the parameter until it is received.

4

I believe that converting the boolean array to a single byte involves many Bite to Bite (arithmetic shift) drive operations, which are usually complex to understand and maintain, unless you have extensive experience with it. Probably the result but simple is an array of bytes, which you can use in the stream you want, as in the example below:

@Test
public void testConvert() throws Exception{
    boolean[] esperado = {true, false, false, true, true, false, false, true};
    byte[] result;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);

    oos.writeObject(esperado);

    oos.flush(); 
    result = bos.toByteArray();

    Assert.assertNotNull(result);
    System.out.println(result.length);

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(result));

    boolean[] obtido = (boolean[]) ois.readObject();

    for(int i = 0; i < esperado.length; i++){
        Assert.assertEquals(esperado[i], obtido[i]);
        System.out.println(esperado[i]);
    }
}

Remembering that instead of Bytearrayoutputstream you can use Fileoutputstream directly or, as stated above, any type of stream you want.

However, although I don’t know exactly what you need this solution for, I believe there may be more elegant ways to solve your problem.

I hope I’ve helped.

  • Where do you convert the Boolean array to a single byte in that code? I am seeing that it is converting into a byte array, giving different result than probably the author expects.

  • That’s what the text says before the code, good weekend.

  • Right, but the code of the other answer shows that yes is possible :), anyway, does not invalidate your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.