Java XML Hex byteArrayToHex(final byte[] arr)

Here you can find the source of byteArrayToHex(final byte[] arr)

Description

Converts a byte array into a hex representation with a space between each byte e.g 00 00 01 00 05 59 B3

License

Apache License

Parameter

Parameter Description
arr The byte array to convert

Return

The byte array as a string of hex values separated by a spaces

Declaration

public static String byteArrayToHex(final byte[] arr) 

Method Source Code


//package com.java2s;
/*//www  . jav  a2 s .  c o  m
 * Copyright 2016 Crown Copyright
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.xml.bind.DatatypeConverter;

public class Main {
    /**
     * Converts a byte array into a hex representation with a space between each
     * byte e.g 00 00 01 00 05 59 B3
     *
     * @param arr The byte array to convert
     * @return The byte array as a string of hex values separated by a spaces
     */
    public static String byteArrayToHex(final byte[] arr) {
        final StringBuilder sb = new StringBuilder();
        if (arr != null) {
            for (final byte b : arr) {
                final byte[] oneByteArr = new byte[1];
                oneByteArr[0] = b;
                sb.append(DatatypeConverter.printHexBinary(oneByteArr));
                sb.append(" ");
            }
        }
        return sb.toString().replaceAll(" $", "");
    }
}

Related

  1. byteArrayToHexString(byte[] bytes)
  2. bytesToHex(byte[] b)
  3. bytesToHex(byte[] bytes)
  4. bytesToHex(final byte[] bytes)