Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Need binary number to be in '8' bit format

$
0
0
I made a decimal to binary converter and I need the output to be in 8 bit. By this I mean I need it to have leading zeros. For example 5 should be "1010-0000". The current code I wrote only outputs the binary format. This is because my limit is going to be 255.

import java.util.Scanner;

public class ConvertDec2Bin {
     public static void main(String[] args) {

		   // LOCAL CONSTANTS
           final int MAXIMUM = 255;


           //String binary = "";
           int decimal = 0;
           int remainder = 0;

  // Ask user to enter an integer
  System.out.println("Enter integer value: ");


  Scanner scan = new Scanner(System.in);

  // Input users integer
  decimal = scan.nextInt();

  // Outputs users number in decimal form
  System.out.println("You have input: "+decimal);
  scan.useDelimiter("\n");

    StringBuilder sb = new StringBuilder();

		// WHILE the decimal number is greater than 0
	    while(decimal > 0)
	    {
			// The remaineder is equal to the modulus of the decimal
	        remainder = decimal % 2;

	        sb.append(remainder);
	        decimal = decimal / 2;

	    }


        sb.reverse();
	    System.out.println("Binary value is: ");
	    System.out.println(sb);




 }

}



Any ideas will be appreciated.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>