Java Bit Set setBit(final byte pData, final int pBitIndex, final boolean pOn)

Here you can find the source of setBit(final byte pData, final int pBitIndex, final boolean pOn)

Description

Method used to set a bit index to 1 or 0.

License

Apache License

Parameter

Parameter Description
pData data to modify
pBitIndex index to set
pOn set bit at specified index to 1 or 0

Return

the modified byte

Declaration

public static byte setBit(final byte pData, final int pBitIndex, final boolean pOn) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from  w w  w.  j a va2  s . com
     * Method used to set a bit index to 1 or 0.
     * 
     * @param pData
     *            data to modify
     * @param pBitIndex
     *            index to set
     * @param pOn
     *            set bit at specified index to 1 or 0
     * @return the modified byte
     */
    public static byte setBit(final byte pData, final int pBitIndex, final boolean pOn) {
        if (pBitIndex < 0 || pBitIndex > 7) {
            throw new IllegalArgumentException(
                    "parameter 'pBitIndex' must be between 0 and 7. pBitIndex=" + pBitIndex);
        }
        byte ret = pData;
        if (pOn) { // Set bit
            ret |= 1 << pBitIndex;
        } else { // Unset bit
            ret &= ~(1 << pBitIndex);
        }
        return ret;
    }
}

Related

  1. setBit(byte[] data, int pos, boolean val)
  2. setBit(byte[] data, int pos, int val)
  3. setBit(byte[] data, int pos, int val)
  4. setBit(byte[] data, long pos, byte val)
  5. setBit(final byte input, final int bit, final boolean status)
  6. setBit(final byte[] buf, final long bitIndex, final boolean value)
  7. setbit(final int num, final int bitnum, final boolean state)
  8. setBit(final int source, final int bit, final boolean value)
  9. setBit(final long word, final int idx, final boolean bit)