Android Bit Set setBit(byte bite, int offset, boolean set)

Here you can find the source of setBit(byte bite, int offset, boolean set)

Description

Modifies the specified bit within the passed byte to 1 or 0 depending on the boolean passed.

Parameter

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.

Return

the modified byte.

Declaration

public static byte setBit(byte bite, int offset, boolean set) 

Method Source Code

//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;
    }
}

Related

  1. setBit(byte bits, int offset, boolean status)
  2. resetBit(byte b, int bit)
  3. setBit(byte[] arr, int bit)
  4. setBit(byte[] bytes, int bitNr, int bit)