1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
|
#include <stdio.h> #include <malloc.h> #include <string.h> #include <stdlib.h> #include <sys/time.h>
#define LIST_SIZE 256
#define FOREST_SIZE (LIST_SIZE * 2 - 1)
#define CODE_MAX 2048
#define PATH_MAX 1024
const char FILE_HEADER_FLAG[] = { 'F', 'X' };
enum { NODE_FLAG_ROOT, NODE_FLAG_LEFT, NODE_FLAG_RIGHT };
enum { NODE_TYPE_DATA, NODE_TYPE_BLANK };
enum { FILE_TYPE_NULL, FILE_TYPE_ENCODE, FILE_TYPE_DECODE, };
typedef unsigned char Byte;
typedef struct _tNode { int type; int data; int weight; char code[CODE_MAX]; struct _tNode* left; struct _tNode* right; }Node, * pNode;
typedef struct _tHuffmanTree { pNode root; int total ; }HuffmanTree, * pHuffmanTree;
struct timeval startTimestamp() { struct timeval stamp; gettimeofday(&stamp, NULL); return stamp; }
double endTimestamp(struct timeval start) { int diff_sec = 0; double start_msec = 0; double end_msec = 0; struct timeval end; gettimeofday(&end, NULL); diff_sec = (int)(end.tv_sec - start.tv_sec); start_msec = (double)start.tv_usec / 1000.0; end_msec = (diff_sec * 1000) + ((double)end.tv_usec / 1000.0); return (end_msec - start_msec); }
pNode createDataNode(int data, int weight) { pNode node = (pNode)malloc(sizeof(Node)); memset(node, 0, sizeof(Node)); node->type = NODE_TYPE_DATA; node->data = data; node->weight = weight; return node; }
pNode createBlankNode(int weight) { pNode node = (pNode)malloc(sizeof(Node)); memset(node, 0, sizeof(Node)); node->type = NODE_TYPE_BLANK; node->weight = weight; return node; }
void addNodeToList(pNode nodelist[], int size, pNode node) { int index; for (index = 0; index < size; ++index) { if (nodelist[index] == NULL) { nodelist[index] = node; break; } } }
pNode popMinNodeFromList(pNode nodelist[], int size) { int min = -1; int index; for (index = 0; index < size; ++index) { if (nodelist[index]) { if (min == -1) { min = index; } else { if (nodelist[min]->weight > nodelist[index]->weight) { min = index; } } } } if (min != -1) { pNode node = nodelist[min]; nodelist[min] = NULL; return node; } return NULL; }
void generateHuffmanCode(pNode root) { if (root) { if (root->left) { strcpy(root->left->code, root->code); strcat(root->left->code, "0"); generateHuffmanCode(root->left); } if (root->right) { strcpy(root->right->code, root->code); strcat(root->right->code, "1"); generateHuffmanCode(root->right); } } }
pNode buildHuffmanTree(int times[]) { pNode nodelist[FOREST_SIZE] = { NULL }; pNode root = NULL; struct timeval startstamp = startTimestamp(); int index; for (index = 0; index < LIST_SIZE; ++index) { if (times[index] > 0) { addNodeToList(nodelist, FOREST_SIZE, createDataNode(index, times[index])); } } while (1) { pNode left = popMinNodeFromList(nodelist, FOREST_SIZE); pNode right = popMinNodeFromList(nodelist, FOREST_SIZE); if (right == NULL) { root = left; break; } else { pNode node = createBlankNode(left->weight + right->weight); node->left = left; node->right = right; addNodeToList(nodelist, FOREST_SIZE, node); } } generateHuffmanCode(root); printf(" bulid huffman tree : %lf msc\n", endTimestamp(startstamp)); return root; }
pNode setpHuffmanTree(pNode root, int flag) { switch (flag) { case NODE_FLAG_LEFT: return root->left; case NODE_FLAG_RIGHT: return root->right; } return NULL; }
void destroyHuffmanTree(pNode root) { if (root) { destroyHuffmanTree(root->left); destroyHuffmanTree(root->right); free(root); } }
pNode buildHuffmanTreeFromFile(FILE* input) { int times[LIST_SIZE] = { 0 }; Byte byte; while (fread(&byte, sizeof(byte), 1, input) == 1) { ++times[byte]; } return buildHuffmanTree(times); }
int countHuffmanTreeWeightTotal(pNode root) { int total = 0; if (root) { if (root->type == NODE_TYPE_DATA) { total = root->weight; } total += countHuffmanTreeWeightTotal(root->left); total += countHuffmanTreeWeightTotal(root->right); } return total; }
void convertTreeToList(pNode root, pNode nodelist[]) { if (root) { if (root->type == NODE_TYPE_DATA) { nodelist[root->data] = root; } convertTreeToList(root->left, nodelist); convertTreeToList(root->right, nodelist); } }
int trimNodeList(pNode nodelist[], int size) { int count = 0; int index; for (index = 0; index < size; ++index) { pNode node = nodelist[index]; if (node) { nodelist[count++] = node; } } return count; }
int encodeFileData(pNode root, FILE* input, FILE* output) { int total = 0; int count = 0; if (root) { Byte byte; int buffer = 0; pNode nodelist[LIST_SIZE] = { NULL }; convertTreeToList(root, nodelist); while (fread(&byte, sizeof(byte), 1, input) == 1) { char* cursor = nodelist[byte]->code; while (*cursor) { buffer <<= 1; if (*cursor == '0') { buffer |= 0; } else { buffer |= 1; } ++count; if (count == 8) { Byte byte = (Byte)buffer; fwrite(&byte, sizeof(byte), 1, output); count = 0; buffer = 0; ++total; } ++cursor; } } if (count > 0) { buffer <<= (8 - count); char byte = (char)buffer; fwrite(&byte, 1, 1, output); ++total; } } return total; }
void decodeFileData(pNode root, FILE* input, FILE* output, int count) { if (root) { Byte byte; pNode cursor = root; while (fread(&byte, sizeof(byte), 1, input) == 1) { int buffer = byte; int index; for (index = 0; index < 8; ++index) { buffer <<= 1; if (!cursor->left || !cursor->right) { Byte data = (Byte)cursor->data; fwrite(&data, sizeof(data), 1, output); if (--count == 0) { break; } cursor = root; } if (buffer & ~0xff) { cursor = setpHuffmanTree(cursor, NODE_FLAG_RIGHT); } else { cursor = setpHuffmanTree(cursor, NODE_FLAG_LEFT); } buffer &= 0xff; } } } }
int canShowChar(char ch) { return (ch > 32 && ch < 127); }
void outputHuffmanTree(FILE* output, pNode root, int flag) { if (root) { int index; char content[128] = { 0 }; const char* flagname[] = { "ROOT", "LEFT", "RIGHT" }; int offset = (int)strlen(root->code) - 1; for (index = 0; index < offset; ++index) { if (root->code[index] == '0') { fprintf(output, " │ "); } else { fprintf(output, " "); } } switch (root->type) { case NODE_TYPE_DATA: sprintf(content, "> %-6s #%-4d 0x%02X : '%c'", flagname[flag], root->weight, root->data, canShowChar((char)root->data) ? root->data : ' '); break; case NODE_TYPE_BLANK: sprintf(content, "[+] %-6s #%-4d", flagname[flag], root->weight); break; } switch (flag) { case NODE_FLAG_ROOT: fprintf(output, "%s", content); break; case NODE_FLAG_LEFT: fprintf(output, " ├─%s", content); break; case NODE_FLAG_RIGHT: fprintf(output, " └─%s", content); break; } if (root->type == NODE_TYPE_DATA) { fprintf(output, " CODE : %s\n", root->code); } else { fprintf(output, "\n"); } outputHuffmanTree(output, root->left, NODE_FLAG_LEFT); outputHuffmanTree(output, root->right, NODE_FLAG_RIGHT); } }
void printHuffmanTree(FILE* output, pNode root) { fprintf(output, " *******************************\n"); fprintf(output, " Print Huffman Tree\n"); fprintf(output, "\n"); outputHuffmanTree(output, root, NODE_FLAG_ROOT); fprintf(output, "\n"); }
void printHuffmanList(FILE* output, pNode root) { pNode nodelist[LIST_SIZE] = { NULL }; int index; int listcount = 0; convertTreeToList(root, nodelist); listcount = trimNodeList(nodelist, LIST_SIZE); fprintf(output, " *******************************\n"); fprintf(output, " # Print Huffman Code List #\n"); fprintf(output, "\n"); fprintf(output, " Total : %d\n", listcount); fprintf(output, "\n"); fprintf(output, " %-7s%-10s%-10s%s\n", "ASCII", "Char", "Weight", "Code"); for (index = 0; index < listcount; ++index) { pNode node = nodelist[index]; Byte ch = (Byte)node->data; if (canShowChar((char)ch)) { fprintf(output, " %-7d%-10c%-10d%s\n", ch, ch, node->weight, node->code); } else { fprintf(output, " %-7d%-10s%-10d%s\n", ch, "NOShow", node->weight, node->code); } } printf("\n"); }
void contUserInputTimes(int times[]) { int index, count; printf(" *******************************\n"); printf(" # Input data to test #\n"); printf("\n"); printf(" Number of input nodes : "); scanf("%d", &count); printf(" Enter the letters and weights for each node : \n"); for (index = 0; index < count; ++index) { char str[128] = { 0 }; int weight = 0; printf(" Char : "); scanf("%s", str); printf(" Weight : "); scanf("%d", &weight); times[(int)str[0]] = weight; } }
pNode inputDataToBuildHuffmanTreeOption() { int times[LIST_SIZE] = { 0 }; contUserInputTimes(times); return buildHuffmanTree(times); }
int inputOption(int begin, int end) { do { int opt; if (scanf("%d", &opt) == 1) { if (opt >= begin && opt <= end) { return opt; } else { printf(" error : The input range should be between %d and %d.\n", begin, end); } } else { printf(" error : Please enter integer type.\n"); setbuf(stdin, NULL); } } while (1); }
int getFileType(const char filename[]) { int type = FILE_TYPE_NULL; FILE* input = fopen(filename, "rb"); if (input) { char buffer[2] = { 0 }; type = FILE_TYPE_ENCODE; if (fread(buffer, 2, 1, input) == 1) { if (buffer[0] == FILE_HEADER_FLAG[0] && buffer[1] == FILE_HEADER_FLAG[1]) { type = FILE_TYPE_DECODE; } } fclose(input); } return type; }
int writeFileHeader(pNode root, FILE* output) { pNode nodelist[LIST_SIZE] = { NULL }; Byte total = 0; int index; fwrite(FILE_HEADER_FLAG, 2, 1, output); convertTreeToList(root, nodelist);
total = (Byte)(trimNodeList(nodelist, LIST_SIZE) - 1); fwrite(&total, sizeof(total), 1, output); for (index = 0; index <= total; ++index) { pNode node = nodelist[index]; Byte byte = (Byte)node->data; fwrite(&byte, sizeof(byte), 1, output); fwrite(&node->weight, sizeof(node->weight), 1, output); } return (total * 5 + 1 + 2); }
void readFileHeader(FILE* input, int times[]) { Byte total; int index; fseek(input, 2, SEEK_CUR); fread(&total, sizeof(total), 1, input); for (index = 0; index <= total; ++index) { Byte byte; int weight; fread(&byte, sizeof(byte), 1, input); fread(&weight, sizeof(weight), 1, input); times[byte] = weight; } }
void toEncode(pNode root, FILE* input) { char filename[PATH_MAX] = { 0 }; FILE* output = NULL; printf(" *******************************\n"); printf(" # Write File #\n"); printf("\n"); printf(" write file name : "); scanf("%s", filename); output = fopen(filename, "wb"); if (output) { int rawsize = countHuffmanTreeWeightTotal(root); int header_size = writeFileHeader(root, output); if (input) { struct timeval startstamp = startTimestamp(); int compressedsize = encodeFileData(root, input, output); printf("\n"); printf(" Elapsed Time : %lf msc\n", endTimestamp(startstamp)); printf(" Character Set : %d Bytes\n", header_size); printf(" Compressed Data : %d Bytes\n", compressedsize); printf(" Raw Data : %d Bytes\n", rawsize); printf(" Compression Ratio : %.2lf%%\n", (compressedsize / (double)rawsize) * 100); printf("\n"); printf(" Execute successfully.\n"); } else { printf(" error : Failed to read file.\n"); } fclose(output); } else { printf(" error : Failed to write file.\n"); } printf("\n"); }
void toDecode(pNode root, FILE* input) { char filename[PATH_MAX] = { 0 }; FILE* output = NULL; printf(" *******************************\n"); printf(" # Write File #\n"); printf("\n"); printf(" write file name : "); scanf("%s", filename); output = fopen(filename, "wb"); if (output) { struct timeval startstamp = startTimestamp(); decodeFileData(root, input, output, countHuffmanTreeWeightTotal(root)); printf(" Elapsed Time : %lf msc\n", endTimestamp(startstamp)); printf("\n"); printf(" Execute successfully.\n"); fclose(output); } else { printf(" error : Failed to write file.\n"); } printf("\n"); }
void encodeFileOption(const char filename[]) { FILE* input = fopen(filename, "rb"); if (input) { pNode root = buildHuffmanTreeFromFile(input); if (root) { do { int option; printf(" *******************************\n"); printf(" # Encode File #\n"); printf("\n"); printf(" 1 > Print Huffman Tree\n"); printf(" 2 > Print Huffman Code List\n"); printf(" 3 > Encode File\n"); printf(" 0 > Back\n"); printf("\n"); option = inputOption(0, 3); if (option == 0) break; switch (option) { case 1: printHuffmanTree(stdout, root); break; case 2: printHuffmanList(stdout, root); break; case 3: fseek(input, 0, SEEK_SET); toEncode(root, input); break; } } while (1); destroyHuffmanTree(root); } else { printf(" error : Failed to build Huffman tree.\n"); } fclose(input); } else { printf(" error : Failed to read file.\n"); } }
void decodeFileOption(const char filename[]) { FILE* input = fopen(filename, "rb"); if (input) { int tell = 0; int times[LIST_SIZE] = { 0 }; readFileHeader(input, times); tell = (int)ftell(input); pNode root = buildHuffmanTree(times); if (root) { do { int option; printf(" *******************************\n"); printf(" # Decode File #\n"); printf("\n"); printf(" 1 > Print Huffman Tree\n"); printf(" 2 > Print Huffman Code List\n"); printf(" 3 > Decode File\n"); printf(" 0 > Back\n"); printf("\n"); option = inputOption(0, 3); if (option == 0) break; switch (option) { case 1: printHuffmanTree(stdout, root); break; case 2: printHuffmanList(stdout, root); break; case 3: fseek(input, tell, SEEK_SET); toDecode(root, input); break; } } while (1); destroyHuffmanTree(root); } else { printf(" error : Failed to build Huffman tree.\n"); } fclose(input); } else { printf(" error : Failed to read file.\n"); } }
void readFileOption() { char filename[PATH_MAX] = { 0 }; printf(" *******************************\n"); printf(" # Read File #\n"); printf("\n"); printf(" input file name : "); scanf("%s", filename); printf("\n"); switch (getFileType(filename)) { case FILE_TYPE_ENCODE: encodeFileOption(filename); break; case FILE_TYPE_DECODE: decodeFileOption(filename); break; default: printf(" error : Failed to read file.\n"); } }
void inputDataToTestOption() { pNode root = inputDataToBuildHuffmanTreeOption(); if (root) { do { int option; printf(" *******************************\n"); printf("\n"); printf(" 1 > Print Huffman Tree\n"); printf(" 2 > Print Huffman Code List\n"); printf(" 0 > Back\n"); printf("\n"); option = inputOption(0, 2); if (option == 0)break; switch (option) { case 1: printHuffmanTree(stdout, root); break; case 2: printHuffmanList(stdout, root); break; } } while (1); destroyHuffmanTree(root); } }
void huffmanDemo() { do { int option; printf(" *******************************\n"); printf(" # Huffman Tree Demo #\n"); printf("\n"); printf(" 1 > Read file\n"); printf(" 2 > Input data to test\n"); printf(" 0 > Quit\n"); printf("\n"); option = inputOption(0, 2); if (option == 0) break; switch (option) { case 1: readFileOption(); break; case 2: inputDataToTestOption(); break; } } while (1); }
int main() { huffmanDemo(); return 0; }
|