代码之家  ›  专栏  ›  技术社区  ›  Aaron Fi

在Java中,我可以用二进制格式定义一个整数常量吗?

  •  82
  • Aaron Fi  · 技术社区  · 16 年前

    类似于用十六进制或八进制定义整数常量,我能用二进制定义吗?

    8 回复  |  直到 16 年前
        1
  •  153
  •   Russ Hayward    15 年前

    在Java 7中:

    int i = 0b10101010;
    

    旧版本的Java中没有二进制文本(请参阅其他答案以了解替代方案)。

        2
  •  68
  •   Cameron McKenzie    13 年前

    byte fourTimesThree = 0b1100;
    byte data = 0b0000110011;
    short number = 0b111111111111111; 
    int overflow = 0b10101010101010101010101010101011;
    long bow = 0b101010101010101010101010101010111L;
    

    特别是在将类级变量声明为二进制时,使用二进制表示法初始化静态变量也绝对没有问题:

    public static final int thingy = 0b0101;
    

    byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte
    

    int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011;
    long bow = 0b1__01010101__01010101__01010101__01010111L;
    

    这不是很好很干净,更不用说可读性了吗?

    Java 7 and Binary Notation: Mastering the OCP Java Programmer (OCPJP) Exam

        3
  •  54
  •   Ed Swangren    16 年前

    Java中没有二进制文本,但我认为您可以做到这一点(尽管我不明白这一点):

    int a = Integer.parseInt("10101010", 2);
    
        4
  •  18
  •   chgman    15 年前

    Ed Swangren的回答

    public final static long mask12 = 
      Long.parseLong("00000000000000000000100000000000", 2);
    

    long 而不是 int 并添加了修改器,以澄清作为位掩码的可能用法。然而,这种方法有两个不便之处。

    1. 直接键入所有这些零容易出错
    2. 在开发时,结果没有十进制或十六进制格式

    我可以建议另一种方法

    public final static long mask12 = 1L << 12;
    

    long YourClassName.mask12 = 4096 [0x1000]
    

    出现在Eclipse中。您可以定义更复杂的常数,如:

    public final static long maskForSomething = mask12 | mask3 | mask0;
    

    或者明确地

    public final static long maskForSomething = (1L<<12)|(1L<<3)|(1L<<0);
    

    maskForSomething 在开发时仍然可以在Eclipse中使用。

        5
  •  17
  •   pawelzieba    14 年前

    使用二进制常数进行掩蔽

    声明常量:

    public static final int FLAG_A = 1 << 0;
    public static final int FLAG_B = 1 << 1;
    public static final int FLAG_C = 1 << 2;
    public static final int FLAG_D = 1 << 3;
    

    并使用它们

    if( (value & ( FLAG_B | FLAG_D )) != 0){
        // value has set FLAG_B and FLAG_D
    }
    
        6
  •  12
  •   Pierre    16 年前

    在谷歌上搜索“Java文字语法”,你会得到一些条目。

    int i = 0xcafe ; // hexadecimal case
    int j = 045 ;    // octal case
    int l = 42 ;     // decimal case
    
        7
  •  2
  •   sth    14 年前

    如果您想处理大量二进制文件,可以定义一些常量:

    public static final int BIT_0 = 0x00000001;
    public static final int BIT_1 = 0x00000002;
    

    public static final int B_00000001 = 0x00000001;
    public static final int B_00000010 = 0x00000002;
    public static final int B_00000100 = 0x00000004;
    
        8
  •  0
  •   PhiLho    16 年前

    更尴尬的回答是:

    public class Main {
    
        public static void main(String[] args) {
            byte b = Byte.parseByte("10", 2);
            Byte bb = new Byte(b);
            System.out.println("bb should be 2, value is \"" + bb.intValue() + "\"" );
        }
    
    }
    

    哪个输出 [java]bb应为2,值为“2”