How to parse C array in python

910 views Asked by At

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
1

There are 1 answers

0
Andrzej Pronobis On BEST ANSWER

How about just:

[re.sub("/\*.+\*/", "", m).replace('\n', '').strip() for m in re.findall("{(.+?)};", c_file_as_string, re.S)]