Java按位操作工具类
/** * Bit转换工具 */ @SuppressWarnings({"WeakerAccess", "unused"}) public class ConvertBit { /** * 短整型(int16)数据中包含的有效bit数量 */ public static final int BITS_IN_SHORT = 8 /*bits in one byte*/ * 2 /*bytes*/; /** * 整型(int32)数据中包含的有效bit数量 */ public static final int BITS_IN_INT = 8 /*bits in one byte*/ * 4 /*bytes*/; /** * 长整型(int64)数据中包含的有效bit数量 */ public static final int BITS_IN_LONG = 8 /*bits in one byte*/ * 8 /*bytes*/; /** * 从源数据中读取左数指定位置的一位bit值(0或1),不改变源数据 * @param source 源数据 * @param index 指定的索引,[0, BITS_IN_SHORT) * @return 指定索引处的bit值,true表示1,false表示0,如超出索引则始终返回false */ public static boolean readBit(short source, int index) { if (index < 0 || index >= BITS_IN_SHORT) return false; return ((source >>> (BITS_IN_SHORT - 1 - index)) & 0x01) == 0x01; } /** * 更新源数据中的指定位置的一位bit值(0或1),返回更新后的数据,不改变源数据 * @param source 源数据 * @param index 指定的索引,[0, BITS_IN_INT) * @param bitValue 指定索引处的bit值,true表示1,false表示0 * @return 更新后的数据,如索引超出则不改变数据 */ public static short writeBit(short source, int index, boolean bitValue) { if (index < 0 || index >= BITS_IN_SHORT) return source; int flag = 0x01 << (BITS_IN_SHORT - 1 - index); if (bitValue) return (short) ((source | flag) & 0xFFFF); else return (short) ((source & (~flag)) & 0xFFFF); } /** * 从源数据中读取左数指定位置的一位bit值(0或1),不改变源数据 * @param source 源数据 * @param index 指定的索引,[0, BITS_IN_INT) * @return 指定索引处的bit值,true表示1,false表示0,如超出索引则始终返回false */ public static boolean readBit(int source, int index) { if (index < 0 || index >= BITS_IN_INT) return false; return ((source >>> (BITS_IN_INT - 1 - index)) & 0x01) == 0x01; } /** * 更新源数据中的指定位置的一位bit值(0或1),返回更新后的数据,不改变源数据 * @param source 源数据 * @param index 指定的索引,[0, BITS_IN_INT) * @param bitValue 指定索引处的bit值,true表示1,false表示0 * @return 更新后的数据,如索引超出则不改变数据 */ public static int writeBit(int source, int index, boolean bitValue) { if (index < 0 || index >= BITS_IN_INT) return source; int flag = 0x01 << (BITS_IN_INT - 1 - index); if (bitValue) return source | flag; else return source & (~flag); } /** * 从源数据中读取左数指定位置的一位bit值(0或1),不改变源数据 * @param source 源数据 * @param index 指定的索引,[0, BITS_IN_LONG) * @return 指定索引处的bit值,true表示1,false表示0,如超出索引则始终返回false */ public static boolean readBit(long source, int index) { if (index < 0 || index >= BITS_IN_LONG) return false; return ((source >>> (BITS_IN_LONG - 1 - index)) & 0x01) == 0x01; } /** * 更新源数据中的指定位置的一位bit值(0或1),返回更新后的数据,不改变源数据 * @param source 源数据 * @param index 指定的索引,[0, BITS_IN_LONG) * @param bitValue 指定索引处的bit值,true表示1,false表示0 * @return 更新后的数据,如索引超出则不改变数据 */ public static long writeBit(long source, int index, boolean bitValue) { if (index < 0 || index >= BITS_IN_LONG) return source; long flag = ((long) 0x01) << (BITS_IN_LONG - 1 - index); if (bitValue) return source | flag; else return source & (~flag); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步