2 * Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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
18 package org.openflow.util;
20 import java.math.BigInteger;
22 public class HexString {
24 * Convert a string of bytes to a ':' separated hex string
26 * @return "0f:ca:fe:de:ad:be:ef"
28 public static String toHexString(byte[] bytes) {
29 if (bytes == null) return "";
33 for(i=0; i< bytes.length; i++) {
36 tmp = Integer.toHexString(U8.f(bytes[i]));
37 if (tmp.length() == 1)
44 public static String toHexString(long val, int padTo) {
45 char arr[] = Long.toHexString(val).toCharArray();
47 // prepend the right number of leading zeros
49 for (; i < (padTo * 2 - arr.length); i++) {
54 for (int j = 0; j < arr.length; j++) {
56 if ((((i + j) % 2) != 0) && (j < (arr.length - 1)))
62 public static String toHexString(long val) {
63 return toHexString(val, 8);
68 * Convert a string of hex values into a string of bytes
69 * @param values "0f:ca:fe:de:ad:be:ef"
70 * @return [15, 5 ,2, 5, 17]
71 * @throws NumberFormatException If the string can not be parsed
73 public static byte[] fromHexString(String values) throws NumberFormatException {
74 String[] octets = values.split(":");
75 byte[] ret = new byte[octets.length];
77 for(int i = 0; i < octets.length; i++) {
78 if (octets[i].length() > 2)
79 throw new NumberFormatException("Invalid octet length");
80 ret[i] = Integer.valueOf(octets[i], 16).byteValue();
85 public static long toLong(String values) throws NumberFormatException {
86 // Long.parseLong() can't handle HexStrings with MSB set. Sigh.
87 BigInteger bi = new BigInteger(values.replaceAll(":", ""),16);
88 if (bi.bitLength() > 64)
89 throw new NumberFormatException("Input string too big to fit in long: " + values);
90 return bi.longValue();