Implements OIC/OCF resource models for cloud.
[platform/upstream/iotivity.git] / cloud / stack / src / main / java / org / iotivity / cloud / util / Bytes.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22 package org.iotivity.cloud.util;
23
24 import java.nio.ByteBuffer;
25
26 public class Bytes {
27     public static byte[] longTo8Bytes(long l) {
28         ByteBuffer buffer = ByteBuffer.allocate(8);
29         buffer.putLong(l);
30         return buffer.array();
31     }
32
33     public static long bytesToLong(byte[] bytes) {
34         ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
35         if (bytes.length < Long.BYTES) {
36             buffer.put(new byte[Long.BYTES - bytes.length]);
37         }
38         buffer.put(bytes);
39         buffer.flip();
40         return buffer.getLong();
41     }
42
43     public static int bytesToInt(byte[] bytes) {
44         ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
45         if (bytes.length < Integer.BYTES) {
46             buffer.put(new byte[Integer.BYTES - bytes.length]);
47         }
48         buffer.put(bytes);
49         buffer.flip();
50         return buffer.getInt();
51     }
52
53     public static byte[] intToMax4Bytes(int i) {
54         ByteBuffer buffer = ByteBuffer.allocate(4);
55         buffer.putInt(i);
56         buffer.flip();
57         if (buffer.get(0) != 0) {
58             return buffer.array();
59         }
60
61         if (buffer.get(1) != 0) {
62             byte b[] = new byte[3];
63             buffer.get();
64             buffer.get(b);
65             return b;
66         }
67
68         if (buffer.get(2) != 0) {
69             byte b[] = new byte[2];
70             buffer.get();
71             buffer.get();
72             buffer.get(b);
73             return b;
74         }
75
76         return new byte[] { buffer.get(3) };
77     }
78 }