Created
October 20, 2017 10:21
-
-
Save Romain-P/8779d47c8e2a0362138fec84e1e89f0c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package com.company; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| public class Main { | |
| public static void main(String[] args) { | |
| System.out.println(read_vi32(write_vi32(0))); | |
| } | |
| static int read_vi32(byte[] bytes) { | |
| int value = 0; | |
| int bytePart = 0; | |
| boolean still; | |
| int pos = 0; | |
| while (bytePart < Integer.SIZE) { | |
| int curr = bytes[pos++]; | |
| still = (curr & 0b10000000) == 0b10000000; | |
| if (bytePart > 0) | |
| value += ((curr & 0b01111111) << bytePart); | |
| else | |
| value += (curr & 0b01111111); | |
| bytePart += 7; | |
| if (!still) | |
| return value; | |
| } | |
| throw new Error("Too much data"); | |
| } | |
| static byte[] write_vi32(int value) { | |
| if (((value >= 0)) && ((value <= 0b01111111))) { | |
| return new byte[] {(byte) value}; | |
| } | |
| byte bytePart; | |
| int intPart = value; | |
| List<Byte> bytes = new ArrayList<>(); | |
| while (intPart != 0) { | |
| bytePart = (byte) (intPart & 0b01111111); | |
| intPart >>>= 7; | |
| if (intPart > 0) | |
| bytePart |= 0b10000000; | |
| bytes.add(bytePart); | |
| } | |
| byte[] array = new byte[bytes.size()]; | |
| for (int i = 0; i < bytes.size(); i++) | |
| array[i] = bytes.get(i); | |
| return array; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment