集册 Java实例教程 将指定的位设置为一个值

将指定的位设置为一个值

欢马劈雪     最近更新时间:2020-01-02 10:19:05

610
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将指定的位设置为一个值


//package com.nowjava;


public class Main {/**来 自 NowJava.com - 时代Java**/

    public static void main(String[] argv) throws Exception {

        byte value = 2;

        int bit = 2;

        boolean on = true;

        System.out.println(setBit(value, bit, on));

    }


    /**

     * 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);

    }
/** 来自 时   代    Java - nowjava.com**/

    /**

     * 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

     */

    
展开阅读全文