[英]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));
You are confusing storage with presentation. 您将存储与演示混淆了。
int b
has no base, regardless of whether you assign 2
, 0b010
or 0x02
to it. int b
没有基地,无论您指定2
, 0b010
或0x02
到它。 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.