Skip to content

Instantly share code, notes, and snippets.

@JunkMeal
Last active October 18, 2024 20:02
Show Gist options
  • Save JunkMeal/e1b0c60f56f788c2f8162a3f52d38fb9 to your computer and use it in GitHub Desktop.
Save JunkMeal/e1b0c60f56f788c2f8162a3f52d38fb9 to your computer and use it in GitHub Desktop.
static char SEGMENT_BITS = 0x7F; // 1111111
static char CONTINUE_BIT = 0x80; // 1000000
static char SIGN_BIT = 0x40; // 0100000
void sleb128(int32_t x) {
unsigned char buf;
int negative = (x < 0);
while(1) {
buf = x & SEGMENT_BITS; // get the 7 (LSB?)
x >>= 7;
if (negative)
x |= ((uint32_t)~0 << (32-7)); // if negative set the trailing bits as the sign (neg=1)
if ((x == 0 && (buf & SIGN_BIT) == 0) || x == -1 && ((buf & SIGN_BIT) != 0)) {
printf("0x%.2X ", buf);
break;
}
buf |= CONTINUE_BIT;
printf("0x%.2X ", buf);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment