Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
Add Comment
Please, Sign In to add comment