Java: Checking if a bit is 0 or 1 in a long

前端 未结 14 1828
抹茶落季
抹茶落季 2020-11-29 01:14

What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?

14条回答
  •  臣服心动
    2020-11-29 01:56

    I coded a little static class which is doing some of the bit operation stuff.

    public final class Bitfield {
    
      private Bitfield() {}
    
      // ********************************************************************
      // * TEST
      // ********************************************************************
    
      public static boolean testBit(final int pos, final int bitfield) {
          return (bitfield & (1 << pos)) == (1 << pos);
      }
    
      public static boolean testNum(final int num, final int bitfield) {
          return (bitfield & num) == num;
      }
    
      // ********************************************************************
      // * SET
      // ********************************************************************
    
      public static int setBit(final int pos, final int bitfield) {
         return bitfield | (1 << pos);
      }
    
      public static int addNum(final int number, final int bitfield) {
          return bitfield | number;
      }
    
      // ********************************************************************
      // * CLEAR
      // ********************************************************************
    
      public static int clearBit(final int pos, final int bitfield) {
          return bitfield ^ (1 << pos);
      }
    
      public static int clearNum(final int num, final int bitfield) {
          return bitfield ^ num;
      }
    
      }
    

    If there are some questions flying around, just write me an email.

    Good Programming!

提交回复
热议问题