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 public static final BinaryPrefixer B = new BinaryPrefixer(1); 033 034 /** 035 * A length prefixer for up to 65535 chars. The length is encoded with 2 unsigned bytes. 036 */ 037 public static final BinaryPrefixer BB = new BinaryPrefixer(2); 038 039 /** The number of digits allowed to express the length */ 040 private int nBytes; 041 042 public BinaryPrefixer(int nBytes) 043 { 044 this.nBytes = nBytes; 045 } 046 047 048 @Override 049 public void encodeLength(int length, byte[] b) 050 { 051 for (int i = nBytes - 1; i >= 0; i--) { 052 b[i] = (byte)(length & 0xFF); 053 length >>= 8; 054 } 055 } 056 057 @Override 058 public int decodeLength(byte[] b, int offset) 059 { 060 int len = 0; 061 for (int i = 0; i < nBytes; i++) 062 { 063 len = 256 * len + (b[offset + i] & 0xFF); 064 } 065 return len; 066 } 067 068 069 @Override 070 public int getPackedLength() 071 { 072 return nBytes; 073 } 074}