Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    /**
     * @param integer The integer to be converted
     * @param n the number of bits of the output binary
     * @return Array of binary number where arr(0) is the most significant
     */
    public static ArrayList<Boolean> decimalToBinary(Integer integer, int n) {
        ArrayList<Boolean> result = new ArrayList();
        if (integer == 0) {
            result.add(false);
            for (int i = 0; i < n - 1; i++)
                result.add(false);
            Collections.reverse(result);
            return result;
        }
        while (integer != 0) {
            if (integer % 2 != 0)
                result.add(true);
            else
                result.add(false);
            integer = integer / 2;
        }

        // Fill the rest of the bits
        for (int i = 0; i < (n - result.size()); i++)
            result.add(false);
        Collections.reverse(result);
        return result;
    }
}