001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.encoder;
015
016import java.io.ByteArrayOutputStream;
017
018public class ByteArrayUtil {
019
020    // big-endian
021    static void writeInt(byte[] byteArray, int offset, int i) {
022        for (int j = 0; j < 4; j++) {
023            int shift = 24 - j * 8;
024            byteArray[offset + j] = (byte) (i >>> shift);
025        }
026    }
027
028    static void writeInt(ByteArrayOutputStream baos, int i) {
029        for (int j = 0; j < 4; j++) {
030            int shift = 24 - j * 8;
031            baos.write((byte) (i >>> shift));
032        }
033    }
034
035    // big-endian
036    static int readInt(byte[] byteArray, int offset) {
037        int i = 0;
038        for (int j = 0; j < 4; j++) {
039            int shift = 24 - j * 8;
040            i += (byteArray[offset + j] & 0xFF) << shift;
041        }
042        return i;
043    }
044
045    static public String toHexString(byte[] ba) {
046        StringBuilder sbuf = new StringBuilder();
047        for (byte b : ba) {
048            String s = Integer.toHexString((int) (b & 0xff));
049            if (s.length() == 1) {
050                sbuf.append('0');
051            }
052            sbuf.append(s);
053        }
054        return sbuf.toString();
055    }
056
057    static public byte[] hexStringToByteArray(String s) {
058        int len = s.length();
059        byte[] ba = new byte[len / 2];
060
061        for (int i = 0; i < ba.length; i++) {
062            int j = i * 2;
063            int t = Integer.parseInt(s.substring(j, j + 2), 16);
064            byte b = (byte) (t & 0xFF);
065            ba[i] = b;
066        }
067        return ba;
068    }
069}