View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.encoder;
15  
16  import java.io.ByteArrayOutputStream;
17  
18  public class ByteArrayUtil {
19  
20    // big-endian
21    static void writeInt(byte[] byteArray, int offset, int i) {
22      for (int j = 0; j < 4; j++) {
23        int shift = 24 - j * 8;
24        byteArray[offset + j] = (byte) (i >>> shift);
25      }
26    }
27  
28    static void writeInt(ByteArrayOutputStream baos, int i) {
29      for (int j = 0; j < 4; j++) {
30        int shift = 24 - j * 8;
31        baos.write((byte) (i >>> shift));
32      }
33    }
34    
35    // big-endian  
36    static int readInt(byte[] byteArray, int offset) {
37      int i = 0;
38      for (int j = 0; j < 4; j++) {
39        int shift = 24 - j * 8;
40        i += (byteArray[offset + j] & 0xFF) << shift;
41      }
42      return i;
43    }
44    
45    static public String toHexString(byte[] ba) {
46      StringBuffer sbuf = new StringBuffer();
47      for(byte b: ba) {
48        String s = Integer.toHexString( (int)(b & 0xff));
49        if(s.length() == 1) {
50          sbuf.append('0');
51        }
52        sbuf.append(s);
53      }
54      return sbuf.toString();
55    }
56  
57    static public byte[] hexStringToByteArray(String s) {
58      int len = s.length();
59      byte[] ba = new byte[len/2];
60  
61      for(int i = 0; i < ba.length; i++) {
62        int j = i*2;
63        int t = Integer.parseInt(s.substring(j, j+2), 16);
64        byte b = (byte) (t & 0xFF);
65        ba[i] = b;
66      }
67      return ba;
68    }
69  }