Here you can find the source of setBitValue(byte aByte, int bitIndex, int bitValue)
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. |
public static int setBitValue(byte aByte, int bitIndex, int bitValue)
//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; } }