Reputation: 184
A user inputs a string of 8 characters that's then converted to string and put into an array to be played with.
With those 8 digits I'd like to be able to convert them into 32-bit binary e.g
int = 12,345,678
int = -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--;
}
Ive tried using "StudentID = Integer.toBinaryString(sID);" However it does not produce the addition 0's to make up the 32-bits (probaby more efficient). Like this
How am I able to allow all integers to be displayed in a 32-bit string, as well as accept negative numbers (that i can use two complement's negating thing)?
Awesome reference; http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
Upvotes: 3
Views: 11191
Reputation: 34628
For integers, you can use this trick:
String result = Long.toBinaryString( sID & 0xffffffffL | 0x100000000L ).substring(1);
This puts the integer in a long
, adds a single bit to its left, which means that the toBinaryString
will have 33 digits, and then takes the right-hand 32 digits (dropping the extra 1 that was added).
A Java 8 version:
String result = Long.toBinaryString( Integer.toUnsignedLong(sID) | 0x100000000L ).substring(1);
Upvotes: 9