Created
February 28, 2013 08:16
-
-
Save caljim/5055119 to your computer and use it in GitHub Desktop.
整数序列压缩算法,实现了variable bytes codes,参考这里http://en.wikipedia.org/wiki/Variable-width_encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
struct element { | |
struct element *next; | |
unsigned char val; | |
}; | |
struct element ot = {NULL,NULL}; | |
char stack[100] = {0}; | |
int p = 0; | |
void push(char c) | |
{ | |
stack[p++] = c; | |
} | |
char pop() | |
{ | |
return stack[--p]; | |
} | |
void encode(int n[], int len) | |
{ | |
int i,k ; | |
struct element *cur; | |
cur = &ot; | |
for(i = 0; i < len; i++) { | |
k = n[i]; | |
while(k >= 128) { | |
push(k % 128); | |
k = k / 128; | |
} | |
push(k); | |
while(p > 1) { | |
cur->next = malloc(sizeof(struct element)); | |
cur = cur->next; | |
cur->val = pop(); | |
} | |
cur->next = malloc(sizeof(struct element)); | |
cur = cur->next; | |
cur->val = pop() + 128; | |
} | |
return; | |
} | |
void print_bytes(struct element *s) | |
{ | |
while(s != NULL) { | |
printf("%d,",s->val); | |
s = s->next; | |
} | |
printf("\n"); | |
return ; | |
} | |
void decode(struct element *s) | |
{ | |
int e = 0; | |
while(s != NULL) { | |
if(s->val < 128) | |
e = 128 * e + s->val; | |
else { | |
e = 128 * e + (s->val - 128); | |
printf("%d,",e); | |
e = 0; | |
} | |
s = s->next; | |
} | |
printf("\n"); | |
return; | |
} | |
int main() | |
{ | |
int a[5] = {257,130, 16394,5,10}; | |
encode(a,5); | |
printf("加密后:\n"); | |
print_bytes(&ot); | |
printf("原文:\n"); | |
decode(&ot); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment