summaryrefslogtreecommitdiffstats
path: root/utility.cpp
blob: fffe2f8c1f97204d17916307d3714ae870b3199c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// Created by lag1924 on 24.03.17.
//
#include "utility.h"

int VarIntRead(unsigned char *data, size_t &readed) {
    readed = 0;
    int result = 0;
    char read;
    do {
        read = data[readed];
        int value = (read & 0b01111111);
        result |= (value << (7 * readed));

        readed++;
        if (readed > 5) {
            throw "VarInt is too big";
        }
    } while ((read & 0b10000000) != 0);

    return result;
}

size_t VarIntWrite(unsigned int value, unsigned char *data) {
    size_t len = 0;
    do {
        unsigned char temp = (unsigned char) (value & 0b01111111);
        value >>= 7;
        if (value != 0) {
            temp |= 0b10000000;
        }
        data[len] = temp;
        len++;
    } while (value != 0);
    return len;
}

long long int ReadVarLong(unsigned char *data, int &readed) {
    readed = 0;
    long long result = 0;
    unsigned char read;
    do {
        read = data[readed];
        long long value = (read & 0b01111111);
        result |= (value << (7 * readed));

        readed++;
        if (readed > 10) {
            throw "VarLong is too big";
        }
    } while ((read & 0b10000000) != 0);
    return result;
}

unsigned char *WriteVarLong(unsigned long long int value, int &len) {
    unsigned char *data = new unsigned char[10];
    len = 0;
    do {
        unsigned char temp = (unsigned char) (value & 0b01111111);
        value >>= 7;
        if (value != 0) {
            temp |= 0b10000000;
        }
        data[len] = temp;
        len++;
    } while (value != 0);

    return data;
}