Created
March 28, 2021 22:16
-
-
Save theraot/68721fe87194946593934f67bcb1f326 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description
Encode and decode LEB128 (according to what Wikipedia says) in C#.
Try it online.
Output