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 /** LL (2-digit hex nibbles) prefixer instance. */ 030 public static final HexNibblesPrefixer LL = new HexNibblesPrefixer(2); 031 /** LLL (3-digit hex nibbles) prefixer instance. */ 032 public static final HexNibblesPrefixer LLL = new HexNibblesPrefixer(3); 033 private int nDigits; 034 035 /** 036 * Constructs a HexNibblesPrefixer with the given number of digits. 037 * @param nDigits number of hex nibble digits in the length prefix 038 */ 039 public HexNibblesPrefixer(int nDigits) { 040 this.nDigits = nDigits; 041 } 042 043 @Override 044 public void encodeLength(int length, byte[] b) { 045 length <<= 1; 046 for (int i = getPackedLength() - 1; i >= 0; i--) { 047 int twoDigits = length % 100; 048 length /= 100; 049 b[i] = (byte)((twoDigits / 10 << 4) + twoDigits % 10); 050 } 051 } 052 053 @Override 054 public int decodeLength(byte[] b, int offset) { 055 int len = 0; 056 for (int i = 0; i < (nDigits + 1) / 2; i++) 057 { 058 len = 100 * len + ((b[offset + i] & 0xF0) >> 4) * 10 + (b[offset + i] & 0x0F); 059 } 060 return len >> 1; 061 } 062 063 @Override 064 public int getPackedLength() 065 { 066 return nDigits + 1 >> 1; 067 } 068}