6 { ['0'] = "0000", ['1'] = "0001", ['2'] = "0010", ['3'] = "0011"
7 , ['4'] = "0100", ['5'] = "0101", ['6'] = "0110", ['7'] = "0111"
8 , ['8'] = "1000", ['9'] = "1001", ['A'] = "1010", ['B'] = "1011"
9 , ['C'] = "1100", ['D'] = "1101", ['E'] = "1110", ['F'] = "1111"
12 struct stream
{ int pos
; char *buf
; };
14 int next(struct stream
*f
)
19 r
=*(f
->buf
++) == '1' ? 1 : 0;
24 unsigned long bin2int(struct stream
*f
, int n
)
27 for (int i
= 0; i
<n
; i
++)
32 unsigned long parse_packet(struct stream
*f
)
34 int packetversion
__attribute__((unused
)) = bin2int(f
, 3);
35 int packettype
= bin2int(f
, 3);
39 if (packettype
== 4) {
41 r
= r
*16+bin2int(f
, 4);
42 r
= r
*16+bin2int(f
, 4);
45 int lengthtypeid
= next(f
);
46 unsigned long packets
[100] = {0};
50 if (lengthtypeid
== 0) {
51 int lengthsubpackets
= bin2int(f
, 15);
53 while (f
->pos
- oldpos
< lengthsubpackets
)
54 packets
[npackets
++] = parse_packet(f
);
57 npackets
= bin2int(f
, 11);
58 for (int i
= 0; i
<npackets
; i
++)
59 packets
[i
] = parse_packet(f
);
62 if (packettype
== 0) { //sum
63 for (int i
= 0; i
<npackets
; i
++)
65 } else if (packettype
== 1) { //product
67 for (int i
= 0; i
<npackets
; i
++)
69 } else if (packettype
== 2) { //minimum
71 for (int i
= 0; i
<npackets
; i
++)
72 r
= packets
[i
] < r
? packets
[i
] : r
;
73 } else if (packettype
== 3) { //maximum
74 for (int i
= 0; i
<npackets
; i
++)
75 r
= packets
[i
] > r
? packets
[i
] : r
;
76 } else if (packettype
== 5) { //greater than
77 r
= packets
[0] > packets
[1];
78 } else if (packettype
== 6) { //less than
79 r
= packets
[0] < packets
[1];
80 } else if (packettype
== 7) { //equal to
81 r
= packets
[0] == packets
[1];
89 struct stream f
= {.pos
=0, .buf
=""};
90 printf("%lu\n", parse_packet(&f
));