LEB(Little Endian Base )128 的编码解码

 LEB128( Little Endian Base 128 ) 是一个变长的数据格式(所占的字节数可变)其分为 unsinged LEB128 和 signed LEB128 。

可用于将一个任意的大整数存储在少量的字节当中。

I.Encoding unsigned LEB128

算法是这样的(Dwarf-2.0.0.pdf Appendix 4 99页)

do
{
  byte = low order 7 bits of value;
  value >>= 7;
  if (value != 0) /* more bytes to come */
    set high order bit of byte;
  emit byte;
} while (value != 0);

Input:unsigned int  a = 12857(0x3239)

output: unsigned LEB128 result

logic:

  1>. 0x3239转为二进制

a = 0000 0000   0000 0000   0011 0010   0011  1001

  2>. 从最低位截取7bit(灰背 景),组成新的字节

byte0  = 0x39

  3>. 原数据高位补7个0

a = 0000 000 0  0000 0000  0000 0000  0110 0100

 4>.if (a != 0),byte |= 0x80

byte0 = 0x39 + 0x80 = 0xB9 

  5>.重复3>,4>,直到a == 0

byte1  = 0x64

a = 0000 000 0  0000 00 00  0000 0000  0000 0000

最终得到结果为:B9 64

II.Decoding unsigned LEB128

算法(Dwarf- 2.0.0.pdf Appendix 4 99页)

  1>.取下一个byte:

bytex = 0xB9

  2>.取其低7位,并放到到第x个7位的位置

result |= (bytex & 0x7F) << (7*x);

  3>.if (!(bytex | 0x80)),继续1>,否则结束。

 byte0  = 0xB9;

result = 0x39;

byte0 & 0x80 == 1

byte1 = 0x64

result = 0x3239

III.LEB128的特点

    1.一个LEB128类型的数据占有的byte数不确定

    2.一个LEB128以字节中最高位是否为0来表示字节流有没有结束。

    3.一个LEB128可能通过编解码与一个unsigned int互相转换。

IV.参考资料:

   1.dwarf-2.0.0.pdf 7.6节 和 Appendix 4 http://dwarfstd.org/

   2.libdwarf Dwarf_leb.c中有LEB128的解码函数。

参考资料:

micklongen的blog:http://blog.chinaunix.net/uid-20704646-id-95934.html

http://en.wikipedia.org/wiki/LEB128


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值