Simple TLV parser
public static String getHexString(byte[] b) throws Exception {
String a="";
for (int i = 0; i < b.length; i++) {
a = a+Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return a;
}
public static String[] getStringArray(String hexString)
{
String[] sr=new String[hexString.length()/2];
for(int i=0;i<hexString.length()-1;i++)
{
if(i%2==0)
sr[i/2]=hexString.substring(i, i+2);
}
return sr;
}
public static String[] dataToStrArray(byte[] b) throws Exception
{
String s=getHexString(b);
String[] sr=getStringArray(s);
return sr;
}
public static void parseTLV(String[] r, String tag)
{
if(tag.length()==2)
{
Integer len=new Integer(0) ;
for(int i=0;i<r.length;i++)
if(r[i].equalsIgnoreCase(tag))
{ //System.out.println("TAG"+tag+"\n Len:"+r[i+1]);
len=Integer.parseInt(r[i+1], 16);
System.out.println();
for (Integer j=1;j<=len;j++)
{
System.out.print(r[i+j+1]+" \t");
}
System.out.println();
}
}
else if(tag.length()==4)
{
Integer len=new Integer(0) ;
String tagHandler;
for(int i=0;i<r.length-1;i++)
{ tagHandler=r[i]+r[i+1];
if(tagHandler.equalsIgnoreCase(tag))
{
System.out.println("TAG"+tagHandler+"\n Len:"+r[i+2]);
len=Integer.parseInt(r[i+2], 16);
System.out.println();
for (Integer j=1;j<=len;j++)
{
System.out.print(r[i+j+2]+" \t");
}
System.out.println();
}
}
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
No comments:
Post a Comment