java指定,Java 将指定的位设置为一个值

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

/**代码未完, 请加载全部代码(NowJava.com).**/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值