package com.its.app.utils;

public class BcdConverter {

    public static String bcdToString(byte bcd) {
        StringBuilder sb = new StringBuilder();
        byte high = (byte)(bcd & 0xf0);
        high >>>= (byte)4;
        high = (byte)(high & 0x0f);
        byte low = (byte) (bcd & 0x0f);

        sb.append(high);
        sb.append(low);

        return sb.toString();
    }

    public static String bcdToString(byte[] data) {
        StringBuilder sb = new StringBuilder();

        for (byte datum : data) {
            sb.append(bcdToString(datum));
        }
        return sb.toString();
    }

    public static byte[] stringToBcd(String data) {
        if ((data.length() % 2) != 0) {
            data += "0";
        }
        byte[] temp = data.getBytes();
        int length = temp.length;
        byte[] result = new byte[length/2];
        for (int ii = 0; ii < length; ii+=2) {
            result[ii/2] = (byte)((temp[ii] - '0') << 4 | (temp[ii+1] - '0'));
        }
        return result;
    }
}
