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
19 public class HexEncode {
21 * This method converts byte array into String format without ":" inserted.
24 * The byte array to convert to string
25 * @return The hexadecimal representation of the byte array. If bytes is
26 * null, "null" string is returned
28 public static String bytesToHexString(byte[] bytes) {
35 StringBuffer buf = new StringBuffer();
36 for (int i = 0; i < bytes.length; i++) {
40 short u8byte = (short) (bytes[i] & 0xff);
41 String tmp = Integer.toHexString(u8byte);
42 if (tmp.length() == 1) {
51 public static String longToHexString(long val) {
52 char arr[] = Long.toHexString(val).toCharArray();
53 StringBuffer buf = new StringBuffer();
54 // prepend the right number of leading zeros
56 for (; i < (16 - arr.length); i++) {
58 if ((i & 0x01) == 1) {
62 for (int j = 0; j < arr.length; j++) {
64 if ((((i + j) & 0x01) == 1) && (j < (arr.length - 1))) {
68 return buf.toString();
72 public static byte[] bytesFromHexString(String values) {
77 String[] octets = target.split(":");
79 byte[] ret = new byte[octets.length];
80 for (int i = 0; i < octets.length; i++) {
81 ret[i] = Integer.valueOf(octets[i], 16).byteValue();
86 public static long stringToLong(String values) {
87 long value = new BigInteger(values.replaceAll(":", ""), 16).longValue();
92 * This method converts byte array into HexString format with ":" inserted.
94 public static String bytesToHexStringFormat(byte[] bytes) {
99 StringBuffer buf = new StringBuffer();
100 for (int i = 0; i < bytes.length; i++) {
104 short u8byte = (short) (bytes[i] & 0xff);
105 String tmp = Integer.toHexString(u8byte);
106 if (tmp.length() == 1) {
111 ret = buf.toString();