fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <cstdio>
  5. using namespace std;
  6.  
  7. class TLV
  8. {
  9. public:
  10.  
  11. string tag;
  12. unsigned int length;
  13. string value;
  14.  
  15. TLV(string data)
  16. {
  17. value = "";
  18. //If there is enough data
  19. if(data.length() >= 4)
  20. {
  21. tag = data.substr(0,2);
  22. sscanf(data.substr(2,4).c_str(),"%2x",&length);
  23.  
  24. //If there is enough data
  25. if(data.length() >= 4 + length*2) value = data.substr(4,length*2);
  26. }
  27. }
  28.  
  29. static void parseTLV(string data, vector<TLV*> &res)
  30. {
  31. while(data.length() >= 4)
  32. {
  33. TLV *t = new TLV(data);
  34. if(t->value == "") break;
  35. res.push_back(t);
  36. data = data.substr(4+(t->length+t->length));
  37. }
  38.  
  39. if(data.length() != 0)
  40. {
  41. //Whole data is not in TLV format. Can throw some error
  42. cout<<"ERROR [1] :: ["<<data<<"]\n";
  43. }
  44. }
  45. };
  46.  
  47.  
  48. int main()
  49. {
  50. string data;// = "0007AAAAAAAAAAAAAA010FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0220AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
  51. cin>>data;
  52. vector<TLV*> res;
  53. TLV::parseTLV(data, res);
  54. for(TLV *t:res)
  55. {
  56. printf("%s | %02X | %s |\n",t->tag.c_str(),t->length,t->value.c_str());
  57. }
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 15240KB
stdin
0002010212431438742295520465365303566540810000.005802NG5917Arinfbnuattest4086005Lagos61052340163049091
stdout
ERROR [1] :: [12431438742295520465365303566540810000.005802NG5917Arinfbnuattest4086005Lagos61052340163049091]
00 | 02 | 0102 |