本文概述
- 二进制字面量示例
- 二进制字面量示例2
在下面的示例中, 我们从整数值创建二进制字面量。
二进制字面量示例
public class BinaryLiteralsExample {
public static void main(String[] args) {
// Binary literal in byte type
byte b1 = 0b101;
// Using b0, The b can be lower or upper case
byte b2 = 0B101;
// Using B0
System.out.println("----------Binary Literal in Byte----------------");
System.out.println("b1 = "+b1);
System.out.println("b2 = "+b2);
// Binary literal in short type
short s1 = 0b101;
// Using b0, The b can be lower or upper case
short s2 = 0B101;
// Using B0
System.out.println("----------Binary Literal in Short----------------");
System.out.println("s1 = "+s1);
System.out.println("s2 = "+s2);
// Binary literal in int type
int i1 = 0b101;
// Using b0, The b can be lower or upper case
int i2 = 0B101;
// Using B0
System.out.println("----------Binary Literal in Integer----------------");
System.out.println("i1 = "+i1);
System.out.println("i2 = "+i2);
// Binary literal in long type
long l1 = 0b0000011111100001;
// Using b0, The b can be lower or upper case
long l2 = 0B0000011111100001;
// Using B0
System.out.println("----------Binary Literal in Long----------------");
System.out.println("l1 = "+l1);
System.out.println("l2 = "+l2);
}
}
输出:
----------Binary Literal in Byte----------------
b1 = 5
b2 = 5
----------Binary Literal in Short----------------
s1 = 5
s2 = 5
----------Binary Literal in Integer----------------
i1 = 5
i2 = 5
----------Binary Literal in Long----------------
l1 = 2017
l2 = 2017
二进制字面量示例2【Java二进制字面量】在此示例中, 我们使用二进制字面量中的下划线并进行操作来创建负二进制。
public class BinaryLiteralsExample {
public static void main(String[] args) {
byte b1 = 5;
// a decimal value
// Using binary of 5
byte b2 = 0b101;
// using b0, The b can be lower or upper case
// Declaring negative binary
byte b3 = -0b101;
// Using underscore in binary literal
byte b4 = 0b101_0;
System.out.println("b1 = "+b1);
System.out.println("b2 = "+b2);
System.out.println("b3 = "+b3);
System.out.println("b4 = "+b4);
// Check whether binary and decimal are equal
System.out.println("is b1 and b2 equal: "+(b1==b2));
// Perform operation on binary value
System.out.println("b2 + 1 = "+(b2+1));
// Perform operation on negative binary value
System.out.println("b3 + 1 = "+(b3+1));
System.out.println("b4 x 2 = "+(b4*2));
}
}
输出:
b1 = 5
b2 = 5
b3 = -5
b4 = 10
is b1 and b2 equal: true
b2 + 1 = 6
b3 + 1 = -4
b4 x 2 = 20
推荐阅读
- Java默认方法
- Java注解类型
- Java 9接口private方法
- Java Base64编码和解码
- Windows 11/10如何修复Snip和Sketch不起作用(解决方法)
- Windows 11如何解决程序没有响应(修复方法教程)
- Windows 11如何修复小部件不工作/加载空白(解决办法)
- 如何修复Windows 11黑屏问题(解决办法教程)
- 如何在Windows 11上禁用OneDrive(方法详细教程)