简体   繁体   English

如何将负数作为二进制分配给java中的int变量?

[英]how to assign negative numbers as binary to int variable in java?

I was seeing how to represent binary numbers in java. 我正在看如何在Java中表示二进制数。 one option is to use as String and use Integer.parseInt() to get the decimal value; 一种选择是用作String并使用Integer.parseInt()获取decimal值;

The other option (assignment of 2 to b ): 另一个选择(将2分配给b ):

int b = 0b0010; //2
System.out.println(b);
System.out.println(Integer.toBinaryString(-2));

output: 输出:

2
11111111111111111111111111111110

using this format, how to represent -2: 使用这种格式,如何表示-2:

int c=??//-b

int values are stored in 32 bits where the most significant bit is the sign. int值存储在32位中,其中最高有效位是符号。

0b0010; //2

is actually 实际上是

0b00000000_00000000_00000000_00000010; //2

To convert that to a negative number, you flip the 0 s to 1 s and the 1 s to 0 s` and add 1. So 要将其转换为负数,请将0 s翻转为1 s,将1 s翻转为0 s`,然后加1。

0b00000000_00000000_00000000_00000010; //2
0b11111111_11111111_11111111_11111101
0b11111111_11111111_11111111_11111110; // +1

And so 所以

int b = 0b11111111_11111111_11111111_11111110;

would have the value -2 . 的值为-2

Use the Bitwise NOT operator: 使用按位NOT运算符:

00000000000000000000000000000010 // 2 = 0b0010
00000000000000000000000000000001 // 1 = 0b0010-0b0001
11111111111111111111111111111110 // ~1 = ~(0b0010-0b0001)

11111111111111111111111111111110 // -2 = ~(0b0010-0b0001)

So you just subtract 0b001 and flip all the bits with the ~ Bitwise operator: 因此,您只需减去0b001并使用~按位运算符将所有位翻转:

int b = ~(0b0010-0b0001); // ~(2-1) = ~1 = -2
System.out.println(b);
System.out.println(Integer.toBinaryString(b));

Demo 演示版

You are confusing storage with presentation. 您将存储与演示混淆了。 int b has no base, regardless of whether you assign 2 , 0b010 or 0x02 to it. int b没有基地,无论您指定20b0100x02到它。 Base 10 is just something println assumes. Base 10只是println假定的。

You can use Integer.toString(number, radix) to print properly signed binary numbers. 您可以使用Integer.toString(number, radix)打印正确签名的二进制数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM