Jub*_*ube 1 java binary twos-complement
用户输入一个 8 个字符的字符串,然后将其转换为字符串并放入要播放的数组中。
有了这 8 位数字,我希望能够将它们转换为 32 位二进制,例如
整数 = 12,345,678
整数 = -10,000,000
1111 1111 0110 0111 0110 1001 1000 0000
System.out.print("Please enter an 8 digit number");
System.out.println();
Scanner user_input = new Scanner( System.in );
StudentID = user_input.nextLine();
sID = Integer.parseInt(StudentID);
String ss[] = StudentID.split("");
StudentID = Integer.toBinaryString(sID);
while(loop >= 0){
d[loop] = Integer.parseInt(ss[loop]) ;
loop--;
}
Run Code Online (Sandbox Code Playgroud)我试过使用“StudentID = Integer.toBinaryString(sID);” 然而,它不会产生加 0 来组成 32 位(可能更有效)。像这样
我如何能够允许所有整数显示在 32 位字符串中,以及接受负数(我可以使用两个补码的否定事物)?
很棒的参考; http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
对于整数,你可以使用这个技巧:
String result = Long.toBinaryString( sID & 0xffffffffL | 0x100000000L ).substring(1);
Run Code Online (Sandbox Code Playgroud)
这将整数放入 a long,在其左侧添加一位,这意味着toBinaryString将有 33 位数字,然后取右手边的 32 位数字(删除添加的额外 1)。
Java 8 版本:
String result = Long.toBinaryString( Integer.toUnsignedLong(sID) | 0x100000000L ).substring(1);
Run Code Online (Sandbox Code Playgroud)