mathajax

Decimal to 8 bit binary conversion

The number system conversion from decimal into binary is carried out by arithmetic operators, modulus and divider. The conversion program has to be given a decimal value which must be in the range from 0 to 255 and it returns binary 8 bits as a result of the conversion.


Decimal to binary 8 bits conversion - Steps

Given a decimal value, decval and converts it into binary 8 bits

  1. modulus decval (the given decimal value) by 2, it returns a reminder ( 0 or 1)
  2. divide decval by 2, it returns a quotient
  3. the quotient becomes the decval
  4. and repeat step 1 to 3 for 8 times
  5. the reminders on each iteration is results binary 8 bits

Decimal to binary 8 bits conversion - Example

 

      Given decimal value = 143 ,convert it into binary 8 bits         
         divide the decimal value by 2 returns a quotient and reminder, 
              the returned quotient becomes decimal value for next division by 2

      divider | quotient | reminder 

         2 | 143  
         -----------    
         2 | 71   | 1
         -----------    
         2 | 35   | 1
         -----------    
         2 | 17   | 1
         -----------    
         2 | 8    | 1
         -----------    
         2 | 4    | 0
         -----------    
         2 | 2    | 0
         -----------    
           | 1    | 0

     decimal value 143 =  binary 8 bits 10001111. 
  

   

Decimal to binary 8 bits conversion - Java programming code

The Java program converts a decimal value between 0 and 255 into binary 8 bits. It reads the decimal value from user at runtime and returns binary 8 bits as result.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Decimal2Binary 
  {

     public static void main(String[] args) throws IOException {
    
     InputStreamReader dis =new InputStreamReader ( System.in );
     BufferedReader br =new BufferedReader(dis);
        
        final int nbits=8;
 System.out.println(" Decimal to 8 bit Binary Conversion \n");
 System.out.println("Enter decimal value");    
        String  inpstr = br.readLine();
 int decval = Integer.parseInt(inpstr); 
        
 StringBuffer strbuf =new StringBuffer();
 for(int n=0;n<nbits;n++) 
   {
      strbuf.append( decval % 2 ) ;
      decval = decval /2;
   }
      
   System.out.println("Binary bits :" + strbuf.reverse());
     }
}

 

Decimal to binary 8 bits conversion - Java program output


Decimal to 8 bit Binary Conversion 

Enter decimal value
67
Binary bits :01000011

Comments

Popular posts from this blog

Solving System of Linear Equations by Gauss Jordan Elimination

Matrix Forward and Back Substitution

Solve System of Linear Equations by LU Decompose

Matrix Determinant by Upper Triangular Matrix

Chebyshev distance between two points