blob: 57776127e7b2228c258e16a818c792d6cd0d410a [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001/**
2* Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
3* University
4*
5* Licensed under the Apache License, Version 2.0 (the "License"); you may
6* not use this file except in compliance with the License. You may obtain
7* a copy of the License at
8*
9* 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, WITHOUT
13* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14* License for the specific language governing permissions and limitations
15* under the License.
16**/
17
18package org.openflow.util;
19
20import java.math.BigInteger;
21
22public class HexString {
23 /**
24 * Convert a string of bytes to a ':' separated hex string
25 * @param bytes
26 * @return "0f:ca:fe:de:ad:be:ef"
27 */
28 public static String toHexString(byte[] bytes) {
29 int i;
30 String ret = "";
31 String tmp;
32 for(i=0; i< bytes.length; i++) {
33 if(i> 0)
34 ret += ":";
35 tmp = Integer.toHexString(U8.f(bytes[i]));
36 if (tmp.length() == 1)
37 ret += "0";
38 ret += tmp;
39 }
40 return ret;
41 }
42
43 public static String toHexString(long val, int padTo) {
44 char arr[] = Long.toHexString(val).toCharArray();
45 String ret = "";
46 // prepend the right number of leading zeros
47 int i = 0;
48 for (; i < (padTo * 2 - arr.length); i++) {
49 ret += "0";
50 if ((i % 2) == 1)
51 ret += ":";
52 }
53 for (int j = 0; j < arr.length; j++) {
54 ret += arr[j];
55 if ((((i + j) % 2) == 1) && (j < (arr.length - 1)))
56 ret += ":";
57 }
58 return ret;
59 }
60
61 public static String toHexString(long val) {
62 return toHexString(val, 8);
63 }
64
65
66 /**
67 * Convert a string of hex values into a string of bytes
68 * @param values "0f:ca:fe:de:ad:be:ef"
69 * @return [15, 5 ,2, 5, 17]
70 * @throws NumberFormatException If the string can not be parsed
71 */
72 public static byte[] fromHexString(String values) throws NumberFormatException {
73 String[] octets = values.split(":");
74 byte[] ret = new byte[octets.length];
75
76 for(int i = 0; i < octets.length; i++) {
77 if (octets[i].length() > 2)
78 throw new NumberFormatException("Invalid octet length");
79 ret[i] = Integer.valueOf(octets[i], 16).byteValue();
80 }
81 return ret;
82 }
83
84 public static long toLong(String values) throws NumberFormatException {
85 // Long.parseLong() can't handle HexStrings with MSB set. Sigh.
86 BigInteger bi = new BigInteger(values.replaceAll(":", ""),16);
87 if (bi.bitLength() > 64)
88 throw new NumberFormatException("Input string too big to fit in long: " + values);
89 return bi.longValue();
90 }
91
92}