Java中有二进制文字吗? [英] Are there binary literals in Java?

查看:25
本文介绍了Java中有二进制文字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用二进制文字声明我的整数.在 Java 中可以吗?

I want to declare my integer number by a binary literal. Is it possible in Java?

推荐答案

从 Java 7 开始,您可以将整数直接表示为二进制数,使用形式 0b (或 0B) 后跟一个或多个二进制数字(0 或 1).例如,0b101010 是整数 42.与八进制和十六进制数一样,二进制文字可以表示负数.

Starting with Java 7 you can represent integer numbers directly as binary numbers, using the form 0b (or 0B) followed by one or more binary digits (0 or 1). For example, 0b101010 is the integer 42. Like octal and hex numbers, binary literals may represent negative numbers.

如果您没有 Java 7,请使用:

If you do not have Java 7 use this:

int val = Integer.parseInt("001101", 2);

还有其他输入整数的方法:

There are other ways to enter integer numbers:

  1. 作为十进制数,例如199551966.-42 等负十进制数实际上是由带有一元否定运算的整数文字组成的表达式.

  1. As decimal numbers such as 1995, 51966. Negative decimal numbers such as -42 are actually expressions consisting of the integer literal with the unary negation operation.

作为八进制数,使用前导 0(零)数字和一个或多个附加八进制数字(0 到 7 之间的数字),例如 077.八进制数可能计算为负数;例如 037777777770 实际上是十进制值 -8.

As octal numbers, using a leading 0 (zero) digit and one or more additional octal digits (digits between 0 and 7), such as 077. Octal numbers may evaluate to negative numbers; for example 037777777770 is actually the decimal value -8.

作为十六进制数,使用形式 0x(或 0X)后跟一个或多个十六进制数字(数字从 0 到 9、a 到 f 或 A 到 F).例如,0xCAFEBABEL 是长整数 3405691582.与八进制数一样,十六进制文字可以表示负数.

As hexadecimal numbers, using the form 0x (or 0X) followed by one or more hexadecimal digits (digits from 0 to 9, a to f or A to F). For example, 0xCAFEBABEL is the long integer 3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.

可以在本维基手册中找到更多详细信息.

More details can be found in this Wikibook.

这篇关于Java中有二进制文字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆