3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.sal.utils;
12 import java.math.BigInteger;
15 * The class provides methods to convert hex encode strings
20 public class HexEncode {
22 * This method converts byte array into String format without ":" inserted.
25 * The byte array to convert to string
26 * @return The hexadecimal representation of the byte array. If bytes is
27 * null, "null" string is returned
29 public static String bytesToHexString(byte[] bytes) {
36 StringBuffer buf = new StringBuffer();
37 for (int i = 0; i < bytes.length; i++) {
41 short u8byte = (short) (bytes[i] & 0xff);
42 String tmp = Integer.toHexString(u8byte);
43 if (tmp.length() == 1) {
52 public static String longToHexString(long val) {
53 char arr[] = Long.toHexString(val).toCharArray();
54 StringBuffer buf = new StringBuffer();
55 // prepend the right number of leading zeros
57 for (; i < (16 - arr.length); i++) {
59 if ((i & 0x01) == 1) {
63 for (int j = 0; j < arr.length; j++) {
65 if ((((i + j) & 0x01) == 1) && (j < (arr.length - 1))) {
69 return buf.toString();
73 public static byte[] bytesFromHexString(String values) {
78 String[] octets = target.split(":");
80 byte[] ret = new byte[octets.length];
81 for (int i = 0; i < octets.length; i++) {
82 ret[i] = Integer.valueOf(octets[i], 16).byteValue();
87 public static long stringToLong(String values) {
88 long value = new BigInteger(values.replaceAll(":", ""), 16).longValue();
93 * This method converts byte array into HexString format with ":" inserted.
95 public static String bytesToHexStringFormat(byte[] bytes) {
100 StringBuffer buf = new StringBuffer();
101 for (int i = 0; i < bytes.length; i++) {
105 short u8byte = (short) (bytes[i] & 0xff);
106 String tmp = Integer.toHexString(u8byte);
107 if (tmp.length() == 1) {
112 ret = buf.toString();