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 * BinaryPrefixer constructs a prefix storing the length in binary.
023 * 
024 * @author joconnor
025 * @version $Revision$ $Date$
026 */
027public class BinaryPrefixer implements Prefixer
028{
029    /**
030         * A length prefixer for up to 255 chars. The length is encoded with 1 unsigned byte.
031         */
032    /**
033     * Pre-built {@link BinaryPrefixer} for common binary length prefix sizes.
034     */
035    public static final BinaryPrefixer B = new BinaryPrefixer(1);
036
037    /**
038     * A length prefixer for up to 65535 chars. The length is encoded with 2 unsigned bytes.
039     */
040    public static final BinaryPrefixer BB = new BinaryPrefixer(2);
041
042    /** The number of digits allowed to express the length */
043    private int nBytes;
044
045    /**
046     * Creates a BinaryPrefixer with the given number of bytes.
047     * @param nBytes the number of bytes used for the length prefix
048     */
049    public BinaryPrefixer(int nBytes)
050    {
051        this.nBytes = nBytes;
052    }
053
054
055    @Override
056    public void encodeLength(int length, byte[] b)
057    {
058        for (int i = nBytes - 1; i >= 0; i--) {
059            b[i] = (byte)(length & 0xFF);
060            length >>= 8;
061        }
062    }
063
064    @Override
065    public int decodeLength(byte[] b, int offset)
066    {
067        int len = 0;
068        for (int i = 0; i < nBytes; i++)
069        {
070            len = 256 * len + (b[offset + i] & 0xFF);
071        }
072        return len;
073    }
074
075
076    @Override
077    public int getPackedLength()
078    {
079        return nBytes;
080    }
081}