Skip to content

Instantly share code, notes, and snippets.

@theraot
Created March 28, 2021 22:16
Show Gist options
  • Save theraot/68721fe87194946593934f67bcb1f326 to your computer and use it in GitHub Desktop.
Save theraot/68721fe87194946593934f67bcb1f326 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
var encoded = LEB128.EncodeSignedLeb128FromInt32(624485);
var str = string.Concat(encoded.Select(entry => entry.ToString("X")));
Console.WriteLine(str);
var result = LEB128.DecodeSignedLeb128(encoded);
Console.WriteLine(result);
}
}
class LEB128
{
public static byte[] EncodeSignedLeb128FromInt32(long value)
{
var result = new List<byte>();
while (true) {
var b = value & 0x7f;
value >>= 7;
if ((value == 0 && (b & 0x40) == 0) || (value == -1 && (b & 0x40) != 0))
{
result.Add((byte)b);
return result.ToArray();
}
result.Add((byte)(b | 0x80));
}
}
public static long DecodeSignedLeb128(byte[] input)
{
var result = 0;
var shift = 0;
foreach (var b in input)
{
result |= (b & 0x7f) << shift;
shift += 7;
if ((0x80 & b) == 0)
{
if (shift < 32 && (b & 0x40) != 0)
{
return result | (~0 << shift);
}
break;
}
}
return result;
}
}
@theraot
Copy link
Author

theraot commented Mar 28, 2021

Description

Encode and decode LEB128 (according to what Wikipedia says) in C#.

Try it online.


Output

E58E26
624485

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment