001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.iso;
020
021/**
022 * HexNibblesPrefixer constructs a prefix storing the length in BCD.
023 * 
024 * @author joconnor, apr
025 * @version $Revision$ $Date$
026 */
027@SuppressWarnings("unused")
028public class HexNibblesPrefixer implements Prefixer {
029    public static final HexNibblesPrefixer LL = new HexNibblesPrefixer(2);
030    public static final HexNibblesPrefixer LLL = new HexNibblesPrefixer(3);
031    private int nDigits;
032
033    public HexNibblesPrefixer(int nDigits) {
034        this.nDigits = nDigits;
035    }
036
037    @Override
038    public void encodeLength(int length, byte[] b) {
039        length <<= 1;
040        for (int i = getPackedLength() - 1; i >= 0; i--) {
041            int twoDigits = length % 100;
042            length /= 100;
043            b[i] = (byte)((twoDigits / 10 << 4) + twoDigits % 10);
044        }
045    }
046
047    @Override
048    public int decodeLength(byte[] b, int offset) {
049        int len = 0;
050        for (int i = 0; i < (nDigits + 1) / 2; i++)
051        {
052            len = 100 * len + ((b[offset + i] & 0xF0) >> 4) * 10 + (b[offset + i] & 0x0F);
053        }
054        return len >> 1;
055    }
056
057    @Override
058    public int getPackedLength()
059    {
060        return nDigits + 1 >> 1;
061    }
062}