Java tutorial
//package com.java2s; /* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2012 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.nio.ByteBuffer; import java.util.Arrays; public class Main { private static String hexOffset(int i) { i = (i >> 4) << 4; int w = i > 0xFFFF ? 8 : 4; try { return zeropad(Integer.toString(i, 16), w); } catch (Exception e) { // should not happen return e.getMessage(); } } /** * left pad with '0' * @param s - original string * @param len - desired len * @return zero padded string * @ if string's length greater than len */ public static String zeropad(String s, int len) { return padleft(s, len, '0'); } /** * zeropads a long without throwing an ISOException (performs modulus operation) * * @param l the long * @param len the length * @return zeropadded value */ public static String zeropad(long l, int len) { try { return padleft(Long.toString((long) (l % Math.pow(10, len))), len, '0'); } catch (Exception ignored) { } return null; // should never happen } /** * pad to the left * @param s - original string * @param len - desired len * @param c - padding char * @return padded string * @ on error */ public static String padleft(String s, int len, char c) { s = s.trim(); if (s.length() > len) throw new RuntimeException("invalid len " + s.length() + "/" + len); StringBuilder d = new StringBuilder(len); int fill = len - s.length(); while (fill-- > 0) d.append(c); d.append(s); return d.toString(); } public static byte[] padLeft(byte[] tgt, int len, byte padding) { if (tgt.length >= len) { return tgt; } ByteBuffer buffer = ByteBuffer.allocate(len); byte[] paddings = new byte[len - tgt.length]; Arrays.fill(paddings, padding); buffer.put(paddings); buffer.put(tgt); return buffer.array(); } /** * trim String (if not null) * @param s String to trim * @return String (may be null) */ public static String trim(String s) { return s != null ? s.trim() : null; } /** * Trims a byte[] to a certain length * @param array the byte[] to be trimmed * @param length the wanted length * @return the trimmed byte[] */ public static byte[] trim(byte[] array, int length) { byte[] trimmedArray = new byte[length]; System.arraycopy(array, 0, trimmedArray, 0, length); return trimmedArray; } }