user21053170
user21053170

Reputation: 39

Decode LEB128 getting wrong results

I'm trying to implement LEB128 to write a custom Minecraft Server implemention. I'm doing so by following Wikipedia article about LEB128 and port example Javascript code given to C. https://en.wikipedia.org/wiki/LEB128

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int leb128(const char* in) {
    int result = 0;
    int shift_counter = 0;
    size_t s = strlen(in);
    int data = atoi(in);
    for(unsigned char i = 0; i < s; i++) {
        const char byte = ((unsigned char*)&data)[i];
        result |= (byte & 0x7f) << i * 7;
        shift_counter += 7;
        if(!(byte & 0x80))  break;
        if((shift_counter < 32 && (byte & 0x40)) != 0) return result |= (~0 << shift_counter);
        
    }
    return result;

}

/* this actually prints bytes makes the int but lazily named it because I renamed every function i took from my og project to avoid revealing the name */
void printInt(int a) {
    int* e = &a;
    puts("\n");
    for(unsigned i = 0; i < sizeof(int); i++) {
        printf(" %d ", ((unsigned char*)e)[i]);
    }

}

int main(void) {
   printInt(leb128("-1"));
   printInt(leb128("255"));
   printInt(leb128("25565"));

   return 0;
}

problem is that I do not receive data in given example table located at https://wiki.vg/Protocol

screenshot from wiki.vg

Input Expected Output
-1 255 255 255 15 255 255 255 255
255 255 1 255 255 255 255
25565 221 199 1 221 255 255 255

What could be I'm doing wrong?

Upvotes: 1

Views: 285

Answers (0)

Related Questions