Guest User

Untitled

a guest
Oct 20th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class Main {
  7.  
  8. public static void main(String[] args) {
  9. System.out.println(read_vi32bis(write_vi32bis(10)));
  10. }
  11.  
  12. static byte[] write_vi32bis(int data) {
  13. if ((data >= 0) && (data <= 0b01111111))
  14. return new byte[] {(byte) data};
  15.  
  16. int c = data;
  17. byte b;
  18.  
  19. List<Byte> bytes = new ArrayList<>();
  20. while (c != 0) {
  21. b = (byte) (c & 0b01111111);
  22. c = c >> 7;
  23.  
  24. if (c > 0)
  25. b = (byte) (b | 0b01111111);
  26.  
  27. bytes.add(b);
  28. }
  29.  
  30. byte[] byteArray = new byte[bytes.size()];
  31. for (int index = 0; index < bytes.size(); index++) {
  32. byteArray[index] = bytes.get(index);
  33. }
  34.  
  35. return byteArray;
  36. }
  37.  
  38. static int read_vi32bis(byte[] bytes) {
  39. byte b;
  40. int value = 0;
  41. int offset = 0;
  42. boolean hasNext;
  43. int pos = 0;
  44.  
  45. do {
  46. b = bytes[pos++];
  47. hasNext = (b & 0b10000000) == 0b10000000;
  48. value = offset > 0
  49. ? (value + ((b & 0b01111111) << offset))
  50. : (value + (b & 0b01111111));
  51. offset += 7;
  52. } while (hasNext);
  53.  
  54. return value;
  55. }
  56.  
  57. static int read_vi32(byte[] bytes) {
  58. int res = 0;
  59. for (int i = 0; i < 4; i++) {
  60. byte b = bytes[i];
  61. if ((b & 0b10000000) != 0) {
  62. break;
  63. }
  64. res = (res << 7) | (b & 0b01111111);
  65. }
  66. return res;
  67. }
  68.  
  69. static byte[] write_vi32(int res) {
  70. int i = 0;
  71. byte[] bytes = new byte[4];
  72. do {
  73. int res1 = res & 0b01111111;
  74. res = res >> 7;
  75. bytes[i] = (byte) (res1 | (res != 0 ? 0b10000000 : 0));
  76. i++;
  77. } while (i < 4 && res != 0);
  78.  
  79. return bytes;
  80. }
  81. }
Add Comment
Please, Sign In to add comment