Skip to content

Instantly share code, notes, and snippets.

@caljim
Created February 28, 2013 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caljim/5055119 to your computer and use it in GitHub Desktop.
Save caljim/5055119 to your computer and use it in GitHub Desktop.
整数序列压缩算法,实现了variable bytes codes,参考这里http://en.wikipedia.org/wiki/Variable-width_encoding
#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