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

In Java, can I define an integer constant in binary format?(在Java中,我可以用二进制格式定义一个整数常量吗?)
本文介绍了在Java中,我可以用二进制格式定义一个整数常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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.

推荐答案

因此,随着 Java SE 7 的发布,二进制表示法成为开箱即用的标准.如果你对二进制有很好的理解,语法就非常简单明了:

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:

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

现在,如果您真的想变得花哨,您可以将 Java 7 中另一个被称为数字文字的简洁新功能与下划线结合起来.看看这些带有文字下划线的二进制符号的奇特示例:

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:

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?

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

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:

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

这篇关于在Java中,我可以用二进制格式定义一个整数常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)