Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Managing bit flags in an array of bytes

796468Jun 9 2009 — edited Jun 9 2009
In my program, I have a large array of bytes. Some arbitrarily long groups of bytes in this array act as groups of bit flags. I need to be able to retrieve and manipulate these bit flags. I read that the best way to do this is with bitwise operations; something I have never learned before. I wrote methods that seem to work, but because I have never done anything like this before, can someone check my work?

Here is an example program, where the only contents of the byte array is a single two-byte grouping of 16 bit flags:
public class test
{
    static byte[] bytes = new byte[2];
    static byte[] pow2 = {1, 2, 4, 8, 16, 32, 64, -128};
    static byte[] pow2i = {-2, -3, -5, -9, -17, -33, -65, 127};
  
    public static void main(String[] args) throws Exception
    {    
        writeBitFlag(0, 6, true);
        for (int i = 0; i < 16; i++)    
            System.out.println("Flag " + i + ": " + getBitFlag(0, i));
    
        System.out.println();
        writeBitFlag(0, 12, true);
        invertBitFlag(0, 0);
        invertBitFlag(0, 0);  
        invertBitFlag(0, 1);

        for (int i = 0; i < 16; i++)    
            System.out.println("Flag " + i + ": " + getBitFlag(0, i));   
    }//end main
  
    public static boolean getBitFlag(int startAddress, int flag)
    {
        return (bytes[startAddress + flag / 8] & pow2[flag %= 8]) == pow2[flag];
    }//end getBitFlag
        
    public static void invertBitFlag(int startAddress, int flag)
    {
        bytes[startAddress + flag / 8] ^= pow2[flag % 8];
    }//end invertBitFlag
        
    public static void writeBitFlag(int startAddress, int flag, boolean flagVal)
    {
        if (flagVal)
            bytes[startAddress + flag / 8] |= pow2[flag % 8];
        else
            bytes[startAddress + flag / 8] &= pow2i[flag % 8];
    }//end writeBitFlag       
}//end class test
Does this look like the right way to do what I am trying to do?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 7 2009
Added on Jun 9 2009
7 comments
646 views