Created
October 19, 2017 10:11
-
-
Save Romain-P/2df8c5932ae247331b6d739fb234d292 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_vi32bis(write_vi32bis(10))); | |
| } | |
| static byte[] write_vi32bis(int data) { | |
| if ((data >= 0) && (data <= 0b01111111)) | |
| return new byte[] {(byte) data}; | |
| int c = data; | |
| byte b; | |
| List<Byte> bytes = new ArrayList<>(); | |
| while (c != 0) { | |
| b = (byte) (c & 0b01111111); | |
| c = c >> 7; | |
| if (c > 0) | |
| b = (byte) (b | 0b01111111); | |
| bytes.add(b); | |
| } | |
| byte[] byteArray = new byte[bytes.size()]; | |
| for (int index = 0; index < bytes.size(); index++) { | |
| byteArray[index] = bytes.get(index); | |
| } | |
| return byteArray; | |
| } | |
| static int read_vi32bis(byte[] bytes) { | |
| byte b; | |
| int value = 0; | |
| int offset = 0; | |
| boolean hasNext; | |
| int pos = 0; | |
| do { | |
| b = bytes[pos++]; | |
| hasNext = (b & 0b10000000) == 0b10000000; | |
| value = offset > 0 | |
| ? (value + ((b & 0b01111111) << offset)) | |
| : (value + (b & 0b01111111)); | |
| offset += 7; | |
| } while (hasNext); | |
| return value; | |
| } | |
| static int read_vi32(byte[] bytes) { | |
| int res = 0; | |
| for (int i = 0; i < 4; i++) { | |
| byte b = bytes[i]; | |
| if ((b & 0b10000000) != 0) { | |
| break; | |
| } | |
| res = (res << 7) | (b & 0b01111111); | |
| } | |
| return res; | |
| } | |
| static byte[] write_vi32(int res) { | |
| int i = 0; | |
| byte[] bytes = new byte[4]; | |
| do { | |
| int res1 = res & 0b01111111; | |
| res = res >> 7; | |
| bytes[i] = (byte) (res1 | (res != 0 ? 0b10000000 : 0)); | |
| i++; | |
| } while (i < 4 && res != 0); | |
| return bytes; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment