標題說得很清楚了,大概就是這樣。需要注意的是本範例使用指針,是以有些地方會出現 unsafe 的區塊。
廢話不多說,直接貼代碼:
C #:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public class GolombEncoder : MonoBehaviour
{
void Start ()
{
// 碼流 : 哥倫布編碼 0~9 的 16進制編碼資料
byte [] strArray = new byte[] { , , , , , };
int bytePosition = , bitPosition = ;
int dataLengthInBits = strArray.Length * ;
int codeNum = ;
while ((bytePosition * + bitPosition) < dataLengthInBits)
{
unsafe{
codeNum = get_uev_code_num (strArray, &bytePosition, &bitPosition);
print ("ExpoColumb codeNum = " + codeNum);
}
}
}
// 取得 byte 陣列中,指定的陣列位子,的二進制位子的值
// 已知 (0xFF = 1111 1111),是以 bitPosition 會在 0~7 之間
// 是以 return 值隻有 0 或 1,不會有其他數字
unsafe int get_bit_at_position (byte[] buf, int *bytePotion, int *bitPosition)
{
int mask = , val = ;
mask = << ( - *bitPosition);
val = ((buf [*bytePotion] & mask) != ) ? : ;
if (++*bitPosition > ) {
*bytePotion = *bytePotion + ;
*bitPosition = ;
}
return val;
}
// 指數哥倫布編碼
unsafe int get_uev_code_num (byte[] buf, int *bytePotion, int *bitPosition)
{
int val = , prefixZeroCount = ;
int prefix = , surfix = ;
while (true) {
val = get_bit_at_position (buf, bytePotion, bitPosition);
if (val == ) {
prefixZeroCount++;
} else {
break;
}
}
prefix = ( << prefixZeroCount) - ;
for (int i = ; i < prefixZeroCount; i++) {
val = get_bit_at_position (buf, bytePotion, bitPosition);
surfix += val * ( << (prefixZeroCount - i - ));
}
prefix += surfix;
return prefix;
}
}
輸出結果:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2Lc1TPB5UeNRkT0cGRPpHOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TM3gTM1QTM2ETOyQDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)