1 11 package com.sun.jmx.snmp.internal; 12 13 import com.sun.jmx.snmp.SnmpDefinitions; 14 20 public class SnmpTools implements SnmpDefinitions { 21 22 27 static public String binary2ascii(byte[] data, int length) 28 { 29 if(data == null) return null; 30 final int size = (length * 2) + 2; 31 byte[] asciiData = new byte[size]; 32 asciiData[0] = (byte) '0'; 33 asciiData[1] = (byte) 'x'; 34 for (int i=0; i < length; i++) { 35 int j = i*2; 36 int v = (data[i] & 0xf0); 37 v = v >> 4; 38 if (v < 10) 39 asciiData[j+2] = (byte) ('0' + v); 40 else 41 asciiData[j+2] = (byte) ('A' + (v - 10)); 42 v = ((data[i] & 0xf)); 43 if (v < 10) 44 asciiData[j+1+2] = (byte) ('0' + v); 45 else 46 asciiData[j+1+2] = (byte) ('A' + (v - 10)); 47 } 48 return new String (asciiData); 49 } 50 51 56 static public String binary2ascii(byte[] data) 57 { 58 return binary2ascii(data, data.length); 59 } 60 65 static public byte[] ascii2binary(String str) { 66 if(str == null) return null; 67 String val = str.substring(2); 68 69 int size = val.length(); 70 byte []buf = new byte[size/2]; 71 byte []p = val.getBytes(); 72 73 for(int i = 0; i < (int) (size / 2); i++) 74 { 75 int j = i * 2; 76 byte v = 0; 77 if (p[j] >= '0' && p[j] <= '9') { 78 v = (byte) ((p[j] - '0') << 4); 79 } 80 else if (p[j] >= 'a' && p[j] <= 'f') { 81 v = (byte) ((p[j] - 'a' + 10) << 4); 82 } 83 else if (p[j] >= 'A' && p[j] <= 'F') { 84 v = (byte) ((p[j] - 'A' + 10) << 4); 85 } 86 else 87 throw new Error ("BAD format :" + str); 88 89 if (p[j+1] >= '0' && p[j+1] <= '9') { 90 v += (p[j+1] - '0'); 92 } 94 else if (p[j+1] >= 'a' && p[j+1] <= 'f') { 95 v += (p[j+1] - 'a' + 10); 97 } 99 else if (p[j+1] >= 'A' && p[j+1] <= 'F') { 100 v += (p[j+1] - 'A' + 10); 102 } 104 else 105 throw new Error ("BAD format :" + str); 106 107 buf[i] = (byte) v; 108 } 109 return buf; 110 } 111 } 112 | Popular Tags |