1 22 23 24 package com.mchange.lang; 25 26 import java.io.StringReader ; 27 import java.io.StringWriter ; 28 import java.io.IOException ; 29 30 public final class ByteUtils 31 { 32 public final static short UNSIGNED_MAX_VALUE = (Byte.MAX_VALUE * 2) + 1; 33 34 public static short toUnsigned(byte b) 35 {return (short) (b < 0 ? (UNSIGNED_MAX_VALUE + 1) + b : b);} 36 37 public static String toHexAscii(byte b) 38 { 39 StringWriter sw = new StringWriter (2); 40 addHexAscii(b, sw); 41 return sw.toString(); 42 } 43 44 public static String toHexAscii(byte[] bytes) 45 { 46 int len = bytes.length; 47 StringWriter sw = new StringWriter (len * 2); 48 for (int i = 0; i < len; ++i) 49 addHexAscii(bytes[i], sw); 50 return sw.toString(); 51 } 52 53 public static byte[] fromHexAscii(String s) throws NumberFormatException 54 { 55 try 56 { 57 int len = s.length(); 58 if ((len % 2) != 0) 59 throw new NumberFormatException ("Hex ascii must be exactly two digits per byte."); 60 61 int out_len = len / 2; 62 byte[] out = new byte[out_len]; 63 int i = 0; 64 StringReader sr = new StringReader (s); 65 while (i < out_len) 66 { 67 int val = (16 * fromHexDigit(sr.read())) + fromHexDigit(sr.read()); 68 out[i++] = (byte) val; 69 } 70 return out; 71 } 72 catch (IOException e) 73 {throw new InternalError ("IOException reading from StringReader?!?!");} 74 } 75 76 static void addHexAscii(byte b, StringWriter sw) 77 { 78 short ub = toUnsigned(b); 79 int h1 = ub / 16; 80 int h2 = ub % 16; 81 sw.write(toHexDigit(h1)); 82 sw.write(toHexDigit(h2)); 83 } 84 85 private static int fromHexDigit(int c) throws NumberFormatException 86 { 87 if (c >= 0x30 && c < 0x3A) 88 return c - 0x30; 89 else if (c >= 0x41 && c < 0x47) 90 return c - 0x37; 91 else if (c >= 0x61 && c < 0x67) 92 return c - 0x57; 93 else 94 throw new NumberFormatException ('\'' + c + "' is not a valid hexadecimal digit."); 95 } 96 97 98 99 100 private static char toHexDigit(int h) 101 { 102 char out; 103 if (h <= 9) out = (char) (h + 0x30); 104 else out = (char) (h + 0x37); 105 return out; 107 } 108 109 private ByteUtils() 110 {} 111 } 112 | Popular Tags |