java 二进制前缀,Java二进制字面量

本文概述

Java在Java 7中添加了新功能Binary Literal。我允许你在二进制数字系统中表示整数类型(字节, 短型, 整型和长型)。要指定二进制字面量, 请将前缀0b或0B添加到整数值。

在下面的示例中, 我们从整数值创建二进制字面量。

二进制字面量示例

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

在此示例中, 我们使用二进制字面量中的下划线并进行操作来创建负二进制。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值