指数哥伦布编码
头文件
#ifndef __COLUMBU_UE_H__#define __COLUMBU_UE_H__#include #include typedef struct Bits_Operation {unsigned char (*read_bit)(const char *arr, int *BitPosition, int *BytePosition);} BITS_OPS, *P_BITS_OPS;typedef struct Columbu_Operation {int (*get_ue)(const char *arr, int *BitPosition, int *BytePosition);} COLUMBU_OPS, *P_COLUMBU_OPS;P_COLUMBU_OPS columbufops = NULL;P_BITS_OPS bitsfops = NULL;#endif
主文件
#include "columbu_ue.h"/* 读取单个字节中的位 */static unsigned char read_bit(const char *arr, int *BitPosition, int *BytePosition){int val = (arr[*BytePosition] & (1 << (7 - *(BitPosition)))) == 0 ? 0 : 1;if(*BitPosition < 8) {(*BitPosition)++;} else {(*BytePosition)++;*BitPosition = 0;}return val;}/* 无符号指数哥伦布编码 */static int get_columbu_ue(const char *arr, int *BitPosition, int *BytePosition){unsigned int val = 0;unsigned char Bit;unsigned int PrefixCount = 0;unsigned int Prefix = 0,Suffix = 0;while(1) {Bit = bitsfops->read_bit(arr,BitPosition,BytePosition);if(Bit == 0) {PrefixCount++;} else {break;} }Prefix = (1 << PrefixCount) - 1;for(int i = 0; i < PrefixCount; i++) {Bit = bitsfops->read_bit(arr,BitPosition,BytePosition);Suffix += Bit * (1 << (PrefixCount - i - 1));}val = Prefix + Suffix;return val;}BITS_OPS bits_fops = {.read_bit = read_bit,};COLUMBU_OPS columbu_fops = {.get_ue = get_columbu_ue,};int main(void){char arr[6] = {0x6A,0x62,0x53,0x5A,0x5A,0x5F};int Val = 0;int BitPosition = 0;int BytePosition = 0;int BitLength = sizeof(arr) / sizeof(unsigned char) * 8;bitsfops = &bits_fops;columbufops = &columbu_fops;while(BytePosition * 8 + BitPosition < BitLength) {Val = columbufops->get_ue(arr,&BitPosition,&BytePosition);printf("get_ue = %d\n",Val);}return 0;}