package com.lingniu.ingest.codec;

/** BCD (Binary-Coded Decimal) 编解码。JT/T 808 的手机号、时间戳常用。 */
public final class BcdCodec {

    private BcdCodec() {}

    public static byte[] encode(String decimal) {
        int len = (decimal.length() + 1) / 2;
        byte[] out = new byte[len];
        int idx = decimal.length() % 2;
        if (idx == 1) {
            out[0] = (byte) Character.digit(decimal.charAt(0), 10);
        }
        for (int i = idx; i < decimal.length(); i += 2) {
            int hi = Character.digit(decimal.charAt(i), 10);
            int lo = Character.digit(decimal.charAt(i + 1), 10);
            out[(i + idx) / 2] = (byte) ((hi << 4) | lo);
        }
        return out;
    }

    public static String decode(byte[] bcd) {
        StringBuilder sb = new StringBuilder(bcd.length * 2);
        for (byte b : bcd) {
            sb.append((b >> 4) & 0x0F).append(b & 0x0F);
        }
        return sb.toString();
    }
}
