1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util.vint;
20
21 import java.io.IOException;
22 import java.io.OutputStream;
23
24 import org.apache.hadoop.hbase.classification.InterfaceAudience;
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 @InterfaceAudience.Private
51 public class UFIntTool {
52
53 private static final int NUM_BITS_IN_LONG = 64;
54
55 public static long maxValueForNumBytes(int numBytes) {
56 return (1L << (numBytes * 8)) - 1;
57 }
58
59 public static int numBytes(final long value) {
60 if (value == 0) {
61 return 1;
62 }
63 return (NUM_BITS_IN_LONG + 7 - Long.numberOfLeadingZeros(value)) / 8;
64 }
65
66 public static byte[] getBytes(int outputWidth, final long value) {
67 byte[] bytes = new byte[outputWidth];
68 writeBytes(outputWidth, value, bytes, 0);
69 return bytes;
70 }
71
72 public static void writeBytes(int outputWidth, final long value, byte[] bytes, int offset) {
73 bytes[offset + outputWidth - 1] = (byte) value;
74 for (int i = outputWidth - 2; i >= 0; --i) {
75 bytes[offset + i] = (byte) (value >>> (outputWidth - i - 1) * 8);
76 }
77 }
78
79 private static final long[] MASKS = new long[] {
80 (long) 255,
81 (long) 255 << 8,
82 (long) 255 << 16,
83 (long) 255 << 24,
84 (long) 255 << 32,
85 (long) 255 << 40,
86 (long) 255 << 48,
87 (long) 255 << 56
88 };
89
90 public static void writeBytes(int outputWidth, final long value, OutputStream os) throws IOException {
91 for (int i = outputWidth - 1; i >= 0; --i) {
92 os.write((byte) ((value & MASKS[i]) >>> (8 * i)));
93 }
94 }
95
96 public static long fromBytes(final byte[] bytes) {
97 long value = 0;
98 value |= bytes[0] & 0xff;
99 for (int i = 1; i < bytes.length; ++i) {
100 value <<= 8;
101 value |= bytes[i] & 0xff;
102 }
103 return value;
104 }
105
106 public static long fromBytes(final byte[] bytes, final int offset, final int width) {
107 long value = 0;
108 value |= bytes[0 + offset] & 0xff;
109 for (int i = 1; i < width; ++i) {
110 value <<= 8;
111 value |= bytes[i + offset] & 0xff;
112 }
113 return value;
114 }
115
116 }