1

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

  • 0000 0000 0000 0000 0000 0000 0000 0000

int = 12,345,678

  • 0000 0000 1011 1100 0110 0001 0100 1110

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

  • 101111000110000101001110

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

Jube
  • 162
  • 2
  • 15

1 Answers1

5

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);
RealSkeptic
  • 32,074
  • 7
  • 48
  • 75