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(final byte[] bytes) {
33 StringBuilder buf = new StringBuilder();
34 for (int i = 0; i < bytes.length; i++) {
35 short u8byte = (short) (bytes[i] & 0xff);
36 String tmp = Integer.toHexString(u8byte);
37 if (tmp.length() == 1) {
42 return buf.toString();
45 public static String longToHexString(final long val) {
46 char arr[] = Long.toHexString(val).toCharArray();
47 StringBuilder buf = new StringBuilder();
48 // prepend the right number of leading zeros
50 for (; i < (16 - arr.length); i++) {
52 if ((i & 0x01) == 1) {
56 for (int j = 0; j < arr.length; j++) {
58 if ((((i + j) & 0x01) == 1) && (j < (arr.length - 1))) {
62 return buf.toString();
66 public static byte[] bytesFromHexString(final String values) {
71 String[] octets = target.split(":");
73 byte[] ret = new byte[octets.length];
74 for (int i = 0; i < octets.length; i++) {
75 ret[i] = Integer.valueOf(octets[i], 16).byteValue();
80 public static long stringToLong(final String values) {
81 long value = new BigInteger(values.replaceAll(":", ""), 16).longValue();
86 * This method converts byte array into HexString format with ":" inserted.
88 public static String bytesToHexStringFormat(final byte[] bytes) {
92 StringBuilder buf = new StringBuilder();
93 for (int i = 0; i < bytes.length; i++) {
97 short u8byte = (short) (bytes[i] & 0xff);
98 String tmp = Integer.toHexString(u8byte);
99 if (tmp.length() == 1) {
104 return buf.toString();