2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.liblldp;
11 import java.math.BigInteger;
14 * The class provides methods to convert hex encode strings
18 public class HexEncode {
20 * This method converts byte array into String format without ":" inserted.
23 * The byte array to convert to string
24 * @return The hexadecimal representation of the byte array. If bytes is
25 * null, "null" string is returned
27 public static String bytesToHexString(byte[] bytes) {
34 StringBuffer buf = new StringBuffer();
35 for (int i = 0; i < bytes.length; i++) {
39 short u8byte = (short) (bytes[i] & 0xff);
40 String tmp = Integer.toHexString(u8byte);
41 if (tmp.length() == 1) {
50 public static String longToHexString(long val) {
51 char arr[] = Long.toHexString(val).toCharArray();
52 StringBuffer buf = new StringBuffer();
53 // prepend the right number of leading zeros
55 for (; i < (16 - arr.length); i++) {
57 if ((i & 0x01) == 1) {
61 for (int j = 0; j < arr.length; j++) {
63 if ((((i + j) & 0x01) == 1) && (j < (arr.length - 1))) {
67 return buf.toString();
71 public static byte[] bytesFromHexString(String values) {
76 String[] octets = target.split(":");
78 byte[] ret = new byte[octets.length];
79 for (int i = 0; i < octets.length; i++) {
80 ret[i] = Integer.valueOf(octets[i], 16).byteValue();
85 public static long stringToLong(String values) {
86 long value = new BigInteger(values.replaceAll(":", ""), 16).longValue();
91 * This method converts byte array into HexString format with ":" inserted.
93 public static String bytesToHexStringFormat(byte[] bytes) {
98 StringBuffer buf = new StringBuffer();
99 for (int i = 0; i < bytes.length; i++) {
103 short u8byte = (short) (bytes[i] & 0xff);
104 String tmp = Integer.toHexString(u8byte);
105 if (tmp.length() == 1) {
110 ret = buf.toString();