提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将指定的位获取为字节值
//package com.nowjava; /* 时 代 J a v a - nowjava.com 提供 */ public class Main { public static void main(String[] argv) throws Exception { byte value = 2; int bit = 2; System.out.println(getBit(value, bit)); } /** * gets the specified bit to a value * @param value the value to check * @param bit the bit number * @return if this bit is on */ public static boolean getBit(byte value, int bit) { if (bit < 0 || bit >= 8) throw new IllegalArgumentException("invalid bit position");/*来 自 nowjava - 时 代 Java*/ byte pos = (byte) (1 << bit); return (value & pos) != 0; } /** * sets the specified bit to a value * @param value the value to check * @param bit the bit number * @return if this bit is on */ public static boolean getBit(short value, int bit) { if (bit < 0 || bit >= 16) throw new IllegalArgumentException("invalid bit position"); short pos = (short) (1 << bit); return (value & pos) != 0; } /** * sets the specified bit to a value * @param value the value to check * @param bit the bit number * @return if this bit is on */ public static boolean getBit(int value, int bit) { if (bit < 0 || bit >= 32) throw new IllegalArgumentException("invalid bit position"); int pos = 1 << bit; return (value & pos) != 0; } /** * sets the specified bit to a value * @param value the value to check * @param bit the bit number * @return if this bit is on */