01: /*
02:
03: Copyright 2004, Martian Software, Inc.
04:
05: Licensed under the Apache License, Version 2.0 (the "License");
06: you may not use this file except in compliance with the License.
07: You may obtain a copy of the License at
08:
09: http://www.apache.org/licenses/LICENSE-2.0
10:
11: Unless required by applicable law or agreed to in writing, software
12: distributed under the License is distributed on an "AS IS" BASIS,
13: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: See the License for the specific language governing permissions and
15: limitations under the License.
16:
17: */
18:
19: package com.martiansoftware.nailgun;
20:
21: /**
22: * Provides a couple of utility methods that help in reading/writin
23: * chunks of data in the Nailgun protocol.
24: *
25: * @author <a href="http://www.martiansoftware.com/contact.html">Marty Lamb</a>
26: */
27: class LongUtils {
28:
29: /**
30: * Encodes the specified long in 4 consecutive bytes (big-endian)
31: * in the specified array, beginning at the specified offset.
32: * @param l the long to encode
33: * @param b the array into which the long should be written
34: * @param offset the offset into the array at which the writing
35: * should begin
36: */
37: public static void toArray(long l, byte[] b, int offset) {
38: b[offset + 3] = (byte) (l % 256);
39: l >>>= 8;
40: b[offset + 2] = (byte) (l % 256);
41: l >>>= 8;
42: b[offset + 1] = (byte) (l % 256);
43: l >>>= 8;
44: b[0] = (byte) (l % 256);
45: }
46:
47: /**
48: * Reads a 4-byte big-endian long from the specified array,
49: * beginnin at the specified offset.
50: * @param b the array containing the encoded long
51: * @param offset the offset into the array at which the encoded
52: * long begins
53: * @return the decoded long
54: */
55: public static long fromArray(byte[] b, int offset) {
56: return (((long) (b[offset] & 0xff) << 24)
57: + ((long) (b[offset + 1] & 0xff) << 16)
58: + ((long) (b[offset + 2] & 0xff) << 8) + ((long) (b[offset + 3] & 0xff)));
59: }
60: }
|