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

时间:2021-04-03 22:34:12

Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?

类似于如何定义十六进制或八进制的整数常量,我可以用二进制来完成吗?

I admit this is a really easy (and stupid) question. My google searches are coming up empty.

我承认这是一个非常简单(和愚蠢)的问题。我的谷歌搜索空无一人。

8 个解决方案

#1


59  

So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary:

因此,随着Java SE 7的发布,二进制表示法开箱即用。如果您对二进制有一个很好的理解,那么语法非常简单明了。

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

And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either:

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

public static final int thingy = 0b0101;

Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:

请注意不要使用太多数据溢出数字,否则您将收到编译器错误:

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

Now, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores:

现在,如果你真的想要花哨,你可以将Java 7中另一个简洁的新功能(称为数字文字与下划线)结合起来。用文字下划线看看这些二进制表示法的奇特例子:

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

Now isn't that nice and clean, not to mention highly readable?

现在不是那么干净,更不用说高度可读了吗?

I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details:

我从TheServerSide上写的关于该主题的一篇小文章中提取了这些代码片段。请随时查看更多详细信息:

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

Java 7和二进制表示法:掌握OCP Java程序员(OCPJP)考试

#2


152  

In Java 7:

在Java 7中:

int i = 0b10101010;

There are no binary literals in older versions of Java (see other answers for alternatives).

旧版Java中没有二进制文字(请参阅其他替代答案)。

#3


52  

There are no binary literals in Java, but I suppose that you could do this (though I don't see the point):

Java中没有二进制文字,但我想你可以这样做(虽然我没有看到这一点):

int a = Integer.parseInt("10101010", 2);

#4


18  

The answer from Ed Swangren

Ed Swangren的回答

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

works fine. I used long instead of int and added the modifiers to clarify possible usage as a bit mask. There are, though, two inconveniences with this approach.

工作正常。我使用long而不是int并添加了修饰符以阐明可能的用法作为位掩码。但是,这种方法有两个不便之处。

  1. The direct typing of all those zeroes is error prone
  2. 直接键入所有这些零是容易出错的
  3. The result is not available in decimal or hex format at the time of development
  4. 在开发时,结果不能以十进制或十六进制格式提供

I can suggest alternative approach

我可以建议替代方法

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

This expression makes it obvious that the 12th bit is 1 (the count starts from 0, from the right to the left); and when you hover mouse cursor, the tooltip

这个表达式很明显第12位是1(计数从0开始,从右到左);当你悬停鼠标光标时,工具提示

long YourClassName.mask12 = 4096 [0x1000]

appears in Eclipse. You can define more complicated constants like:

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

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

or explicitly

或明确地

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

The value of the variable maskForSomething will still be available in Eclipse at development time.

变量maskForSomething的值在开发时仍可在Eclipse中使用。

#5


15  

Using binary constants to masking

Declare constants:

声明常量:

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;

and use them

并使用它们

if( (value & ( FLAG_B | FLAG_D )) != 0){
    // value has set FLAG_B and FLAG_D
}

#6


12  

Search for "Java literals syntax" on Google and you come up with some entries.

在Google上搜索“Java literals syntax”,你会得到一些条目。

There is an octal syntax (prefix your number with 0), decimal syntax and hexadecimal syntax with a "0x" prefix. But no syntax for binary notation.

有一个八进制语法(数字前缀为0),十进制语法和带有“0x”前缀的十六进制语法。但没有二进制表示法的语法。

Some examples:

一些例子:

int i = 0xcafe ; // hexadecimal case
int j = 045 ;    // octal case
int l = 42 ;     // decimal case

#7


2  

If you want to mess around with lots of binary you could define some constants:

如果你想搞乱大量的二进制文件,你可以定义一些常量:

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

etc.

等等

or

要么

public static final int B_00000001 = 0x00000001;
public static final int B_00000010 = 0x00000002;
public static final int B_00000100 = 0x00000004;

#8


0  

Slightly more awkward answer:

稍微尴尬的答案:

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() + "\"" );
    }

}

which outputs [java] bb should be 2, value is "2"

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

#1


59  

So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary:

因此,随着Java SE 7的发布,二进制表示法开箱即用。如果您对二进制有一个很好的理解,那么语法非常简单明了。

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

And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either:

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

public static final int thingy = 0b0101;

Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:

请注意不要使用太多数据溢出数字,否则您将收到编译器错误:

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

Now, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores:

现在,如果你真的想要花哨,你可以将Java 7中另一个简洁的新功能(称为数字文字与下划线)结合起来。用文字下划线看看这些二进制表示法的奇特例子:

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

Now isn't that nice and clean, not to mention highly readable?

现在不是那么干净,更不用说高度可读了吗?

I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details:

我从TheServerSide上写的关于该主题的一篇小文章中提取了这些代码片段。请随时查看更多详细信息:

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

Java 7和二进制表示法:掌握OCP Java程序员(OCPJP)考试

#2


152  

In Java 7:

在Java 7中:

int i = 0b10101010;

There are no binary literals in older versions of Java (see other answers for alternatives).

旧版Java中没有二进制文字(请参阅其他替代答案)。

#3


52  

There are no binary literals in Java, but I suppose that you could do this (though I don't see the point):

Java中没有二进制文字,但我想你可以这样做(虽然我没有看到这一点):

int a = Integer.parseInt("10101010", 2);

#4


18  

The answer from Ed Swangren

Ed Swangren的回答

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

works fine. I used long instead of int and added the modifiers to clarify possible usage as a bit mask. There are, though, two inconveniences with this approach.

工作正常。我使用long而不是int并添加了修饰符以阐明可能的用法作为位掩码。但是,这种方法有两个不便之处。

  1. The direct typing of all those zeroes is error prone
  2. 直接键入所有这些零是容易出错的
  3. The result is not available in decimal or hex format at the time of development
  4. 在开发时,结果不能以十进制或十六进制格式提供

I can suggest alternative approach

我可以建议替代方法

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

This expression makes it obvious that the 12th bit is 1 (the count starts from 0, from the right to the left); and when you hover mouse cursor, the tooltip

这个表达式很明显第12位是1(计数从0开始,从右到左);当你悬停鼠标光标时,工具提示

long YourClassName.mask12 = 4096 [0x1000]

appears in Eclipse. You can define more complicated constants like:

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

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

or explicitly

或明确地

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

The value of the variable maskForSomething will still be available in Eclipse at development time.

变量maskForSomething的值在开发时仍可在Eclipse中使用。

#5


15  

Using binary constants to masking

Declare constants:

声明常量:

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;

and use them

并使用它们

if( (value & ( FLAG_B | FLAG_D )) != 0){
    // value has set FLAG_B and FLAG_D
}

#6


12  

Search for "Java literals syntax" on Google and you come up with some entries.

在Google上搜索“Java literals syntax”,你会得到一些条目。

There is an octal syntax (prefix your number with 0), decimal syntax and hexadecimal syntax with a "0x" prefix. But no syntax for binary notation.

有一个八进制语法(数字前缀为0),十进制语法和带有“0x”前缀的十六进制语法。但没有二进制表示法的语法。

Some examples:

一些例子:

int i = 0xcafe ; // hexadecimal case
int j = 045 ;    // octal case
int l = 42 ;     // decimal case

#7


2  

If you want to mess around with lots of binary you could define some constants:

如果你想搞乱大量的二进制文件,你可以定义一些常量:

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

etc.

等等

or

要么

public static final int B_00000001 = 0x00000001;
public static final int B_00000010 = 0x00000002;
public static final int B_00000100 = 0x00000004;

#8


0  

Slightly more awkward answer:

稍微尴尬的答案:

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() + "\"" );
    }

}

which outputs [java] bb should be 2, value is "2"

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