01: package org.apache.lucene.analysis.payloads;
02:
03: /**
04: * Licensed to the Apache Software Foundation (ASF) under one or more
05: * contributor license agreements. See the NOTICE file distributed with
06: * this work for additional information regarding copyright ownership.
07: * The ASF licenses this file to You under the Apache License, Version 2.0
08: * (the "License"); you may not use this file except in compliance with
09: * the License. You may obtain a copy of the License at
10: *
11: * http://www.apache.org/licenses/LICENSE-2.0
12: *
13: * Unless required by applicable law or agreed to in writing, software
14: * distributed under the License is distributed on an "AS IS" BASIS,
15: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: * See the License for the specific language governing permissions and
17: * limitations under the License.
18: */
19:
20: /**
21: *
22: *
23: **/
24: public class PayloadHelper {
25:
26: public static byte[] encodeFloat(float payload) {
27: return encodeFloat(payload, new byte[4], 0);
28: }
29:
30: public static byte[] encodeFloat(float payload, byte[] data,
31: int offset) {
32: return encodeInt(Float.floatToIntBits(payload), data, offset);
33: }
34:
35: public static byte[] encodeInt(int payload, byte[] data, int offset) {
36: data[offset] = (byte) (payload >> 24);
37: data[offset + 1] = (byte) (payload >> 16);
38: data[offset + 2] = (byte) (payload >> 8);
39: data[offset + 3] = (byte) payload;
40: return data;
41: }
42:
43: /**
44: * @param bytes
45: * @see #decodeFloat(byte[], int)
46: * @see #encodeFloat(float)
47: * @return the decoded float
48: */
49: public static float decodeFloat(byte[] bytes) {
50: return decodeFloat(bytes, 0);
51: }
52:
53: /**
54: * Decode the payload that was encoded using {@link #encodeFloat(float)}.
55: * NOTE: the length of the array must be at least offset + 4 long.
56: * @param bytes The bytes to decode
57: * @param offset The offset into the array.
58: * @return The float that was encoded
59: *
60: * @see # encodeFloat (float)
61: */
62: public static final float decodeFloat(byte[] bytes, int offset) {
63:
64: return Float.intBitsToFloat(decodeInt(bytes, offset));
65: }
66:
67: public static final int decodeInt(byte[] bytes, int offset) {
68: return ((bytes[offset] & 0xFF) << 24)
69: | ((bytes[offset + 1] & 0xFF) << 16)
70: | ((bytes[offset + 2] & 0xFF) << 8)
71: | (bytes[offset + 3] & 0xFF);
72: }
73: }
|