Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

public class Main {
    /**
     * Return a BCD representation of an integer as a 4-byte array.
     * @param i int
     * @return  byte[4]
     */
    public static byte[] intToBcdArray(int i) {
        if (i < 0)
            throw new IllegalArgumentException("Argument cannot be a negative integer.");

        StringBuilder binaryString = new StringBuilder();

        while (true) {
            int quotient = i / 10;
            int remainder = i % 10;
            String nibble = String.format("%4s", Integer.toBinaryString(remainder)).replace(' ', '0');
            binaryString.insert(0, nibble);

            if (quotient == 0) {
                break;
            } else {
                i = quotient;
            }
        }

        return ByteBuffer.allocate(4).putInt(Integer.parseInt(binaryString.toString(), 2)).array();
    }
}