Java Bit Set setBitValue(byte aByte, int bitIndex, int bitValue)

Here you can find the source of setBitValue(byte aByte, int bitIndex, int bitValue)

Description

Sets the bit value of the provided byte at the provided bitIndex (0 <= bitIndex <=7) to the provided bitValue(0 or 1).

License

Apache License

Parameter

Parameter Description
aByte the byte in which the bit should be set
bitIndex an index between 0 and 7 (inclusive)
bitValue is a value of either 0 or 1.

Return

the original byte with the bit at the bitIndex position set to bitValue.

Declaration

public static int setBitValue(byte aByte, int bitIndex, int bitValue) 

Method Source Code

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

public class Main {
    public final static int BITS_PER_BYTE = 8;

    /**//from  w ww.jav  a2  s  .c  om
     * Sets the bit value of the provided byte at the provided bitIndex (0 <= bitIndex <=7) to the provided bitValue(0 or 1).
     * 
     * @param aByte
     *            the byte in which the bit should be set
     * @param bitIndex
     *            an index between 0 and 7 (inclusive)
     * @param bitValue
     *            is a value of either 0 or 1.
     * @return the original byte with the bit at the bitIndex position set to bitValue.
     */
    public static int setBitValue(byte aByte, int bitIndex, int bitValue) {
        if (bitIndex >= BITS_PER_BYTE) {
            throw new ArrayIndexOutOfBoundsException("The provided bitIndex[" + bitIndex
                    + "] is larger than the size of a byte[" + BITS_PER_BYTE + "].");
        }

        if (bitIndex < 0) {
            throw new ArrayIndexOutOfBoundsException(
                    "The provided bitIndex[" + bitIndex + "] must be greater than or equal to zero.");
        }

        byte newByte = (byte) 0;
        if (bitValue == 0) {
            newByte = (byte) (aByte & ~(1 << bitIndex));
        } else if (bitValue == 1) {
            newByte = (byte) (aByte | (1 << bitIndex));
        } else {
            throw new IllegalArgumentException("The provided bitValue[" + bitValue + "] must be either 0 or 1.");
        }

        return newByte;
    }
}

Related

  1. setBits(int value, int bits)
  2. setBits(long value, long bits)
  3. setBitsFromLong(byte[] dst, long dstoff, long l, int off, int len)
  4. setBitsInLong(long l, int n, int k, long v)
  5. setBitTo0(final long word, final int idx)
  6. setBitValueAt(int destination, int value, int index)
  7. setBitWidth(int bw)