Java Bit Set setBit(byte value, int bit, boolean on)

Here you can find the source of setBit(byte value, int bit, boolean on)

Description

sets the specified bit to a value

License

Open Source License

Parameter

Parameter Description
value the base value
bit the bit number
on set it to on or not

Return

value with the bit set

Declaration

public static byte setBit(byte value, int bit, boolean on) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*w  ww  . j  av  a2  s  .  c o  m*/
     * sets the specified bit to a value
     * @param value the base value
     * @param bit the bit number
     * @param on set it to on or not
     * @return value with the bit set
     */
    public static byte setBit(byte value, int bit, boolean on) {
        if (bit < 0 || bit >= 8)
            throw new IllegalArgumentException("invalid bit position");
        byte pos = (byte) (1 << bit);
        if (on)
            return (byte) (value | pos);
        else
            return (byte) (value & ~pos);
    }

    /**
     * sets the specified bit to a value
     * @param value the base value
     * @param bit the bit number
     * @param on set it to on or not
     * @return value with the bit set
     */
    public static short setBit(short value, int bit, boolean on) {
        if (bit < 0 || bit >= 16)
            throw new IllegalArgumentException("invalid bit position");
        short pos = (short) (1 << bit);
        if (on)
            return (short) (value | pos);
        else
            return (short) (value & ~pos);
    }

    /**
     * sets the specified bit to a value
     * @param value the base value
     * @param bit the bit number
     * @param on set it to on or not
     * @return value with the bit set
     */
    public static int setBit(int value, int bit, boolean on) {
        if (bit < 0 || bit >= 32)
            throw new IllegalArgumentException("invalid bit position");
        int pos = 1 << bit;
        if (on)
            return value | pos;
        else
            return value & ~pos;
    }

    /**
     * sets the specified bit to a value
     * @param value the base value
     * @param bit the bit number
     * @param on set it to on or not
     * @return value with the bit set
     */
    public static long setBit(long value, int bit, boolean on) {
        if (bit < 0 || bit >= 64)
            throw new IllegalArgumentException("invalid bit position");
        long pos = 1L << bit;
        if (on)
            return value | pos;
        else
            return value & ~pos;
    }
}

Related

  1. setBit(byte in, int position, boolean value)
  2. setBit(byte input, int bit)
  3. setBit(byte original, int bitToSet)
  4. setBit(byte target, byte pos)
  5. setBit(byte v, int position, boolean value)
  6. setBit(byte value, int bit, boolean state)
  7. setBit(byte value, int bit, boolean state)
  8. setBit(byte[] arr, int bit)
  9. setBit(byte[] b, int index)