算法 - 基础

位操作

  • 获取位
  • 设置位
  • 清除位
  • add操作是否溢出
  • multi操作是否溢出
public static byte getBit(int data, int position) {
     return(byte) ((data >> position) & 1);
}

public static int setBit(int data, int position) {
    return data | (1 << position);
}

public static int clearBit(int data, int position) {
    return data & ~(1 << position);
}

public static boolean beOverflowForIntAdd(int one, int other) {
    int result = one + other;

    return ((result ^ one) & (result ^ other)) < 0;
}

public static boolean beOverflowForIntMulti(int one, int other) {
    int result = one * other;

    return result / one == other;
}
posted @ 2021-11-20 16:59  密云不雨  阅读(22)  评论(0)    收藏  举报