Here you can find the source of setBit(byte bite, int offset, boolean set)
Parameter | Description |
---|---|
bite | byte within which lies the bit to change. |
offset | the bit to change within the byte. |
set | if true then set the bit, else unset the bit. |
public static byte setBit(byte bite, int offset, boolean set)
//package com.java2s; public class Main { /**//w w w . j av a2s . c o m * Modifies the specified bit within the passed byte to 1 or 0 depending on the boolean passed. * The offset should not be greater than 7. * * @param bite byte within which lies the bit to change. * @param offset the bit to change within the byte. * @param set if true then set the bit, else unset the bit. * @return the modified byte. */ public static byte setBit(byte bite, int offset, boolean set) { if (offset > 7 || offset < 0) { throw new IllegalArgumentException( "Offset must be between 0 and 7!"); } if (set) { //bitwise OR will set specified bit to one bite = (byte) (bite | (1 << offset)); } else { //bitwise NOT will set new byte to all ones except the specified bit //then we AND that with the byte to change the specified bit to 0 bite = (byte) (bite & ~(1 << offset)); } return bite; } }