Sunday, 23 March 2014

Post 20: Conversion of byte number to decimal number

The following codes converts bit number to decimal and vice versa. Sorry, for being so short. If you have any questions, don't hesitate to comment. I'll try my best to get back to you.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bitumwandler;

import java.io.IOException;
import java.io.*;
/**
 *
 * @author pad
 */
public class BitUmwandler {
    int bitLaenge=7;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        System.out.println(new BitUmwandler().BitToDecimal("11111010"));
        System.out.println(new BitUmwandler().DecimalToBit(2));
    }
    
    public int BitToDecimal(String bitNumber){        
        String bitString=bitNumber;
        int result=0;
        for (int i=0; i<=bitLaenge; i++){
            if (bitString.substring(i,i+1).equals("1")){
                result+=(int)(Math.pow(2,bitLaenge-i));       
            }
        }
        return result;
    }
    
    public String DecimalToBit(int decimalNumber){
        String byteValue="";
        for (int i=bitLaenge; i>=0; i--){
            if(decimalNumber>=Math.pow(2,i)){
                decimalNumber=decimalNumber-(int)Math.pow(2, i);
                byteValue+="1";
            }else{
                byteValue+="0";
            }
        }
        return  byteValue;
    }
}




Tweet