-1

I've got a file containing the following C arrays:

/* Frame bytes */
static const unsigned char pkt1[19] = {
0x83, 0x01, 0xbc, 0x4e, 0xd9, 0x09, 0x81, 0x03, /* ...N.... */
0x79, 0x54, 0x55, 0x98, 0x69, 0x06, 0x0a, 0x12, /* yTU.i... */
0x42, 0x83, 0x62                                /* B.b */
};

/* Frame bytes */
static const unsigned char pkt2[11] = {
0x83, 0x01, 0xbc, 0x4e, 0x39, 0x09, 0x81, 0x03, /* ...N9... */
0x52, 0x80, 0x30                                /* R.0 */
};

/* Frame (115 bytes) */
static const unsigned char pkt3[27] = {
0x83, 0x01, 0xbc, 0x4e, 0x39, 0x09, 0x81, 0x03, /* ...N9... */
0x01, 0x00, 0x6c, 0x1f, 0xa2, 0x1d, 0x02, 0x01, /* ..l..... */
0x04, 0x08, 0x34, 0x12, 0x21, 0x00, 0x35, 0x63, /* ..4.!.5c */
0x92, 0x91, 0x65                                /* ..e */
};

Is there any straightforward way in python to parse this file and extract the hex streams? I need the output to be something like this:

0x83, 0x01, 0xbc, 0x4e, 0xd9, 0x09, 0x81, 0x03, 0x79, 0x54, 0x55, 0x98, 0x69, 0x06, 0x0a, 0x12, 0x42, 0x83, 0x62

0x83, 0x01, 0xbc, 0x4e, 0x39, 0x09, 0x81, 0x03, 0x52, 0x80, 0x30

0x83, 0x01, 0xbc, 0x4e, 0x39, 0x09, 0x81, 0x03, 0x01, 0x00, 0x6c, 0x1f, 0xa2, 0x1d, 0x02, 0x01, 0x04, 0x08, 0x34, 0x12, 0x21, 0x00, 0x35, 0x63, 0x92, 0x91, 0x65

Or:

8301bc4ed90981037954559869060a12428362   
8301bc4e39098103528030   
8301bc4e3909810301006c1fa21d02010408341221003563929165
Mazdak
  • 105,000
  • 18
  • 159
  • 188
B Faley
  • 17,120
  • 43
  • 133
  • 223
  • 1
    In general you would have to write a C parser in Python. Something really difficult. But if the file is as simple as we see then you could simply search for everything between `{...};` via regular expressions. – freakish Jun 24 '15 at 06:11
  • @freakish Searching for `{...}` blocks was my first thought too. Just wanted to see if there is any lib in python which could understands C arrays. Seems there is not. – B Faley Jun 24 '15 at 06:14
  • `:%s,/.*/,` `:g/{/norm jvi}J` `:g/[{}]/d` in Vim. – TessellatingHeckler Jun 24 '15 at 06:15

1 Answers1

4

How about just:

[re.sub("/\*.+\*/", "", m).replace('\n', '').strip() for m in re.findall("{(.+?)};", c_file_as_string, re.S)]
Andrzej Pronobis
  • 33,828
  • 17
  • 76
  • 92