Java ByteBuffer to Hex bytesToHex(ByteBuffer bytes)

Here you can find the source of bytesToHex(ByteBuffer bytes)

Description

bytes To Hex

License

Apache License

Declaration

public static String bytesToHex(ByteBuffer bytes) 

Method Source Code

//package com.java2s;
/**//from www.j  av  a2s .co m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 java.nio.ByteBuffer;

import java.util.Arrays;

import java.util.Map;

public class Main {
    public static String bytesToHex(byte... bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            int bint = b & 0xff;
            if (bint <= 0xF)
                // toHexString does not 0 pad its results.
                sb.append("0");
            sb.append(Integer.toHexString(bint));
        }
        return sb.toString();
    }

    public static String bytesToHex(ByteBuffer bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.position() + bytes.arrayOffset(); i < bytes.limit() + bytes.arrayOffset(); i++) {
            int bint = bytes.array()[i] & 0xff;
            if (bint <= 0xF)
                // toHexString does not 0 pad its results.
                sb.append("0");
            sb.append(Integer.toHexString(bint));
        }
        return sb.toString();
    }

    public static String toString(Map<?, ?> map) {
        // wtf, why isn't something like this in guava or commons collections?
        StringBuilder sb = new StringBuilder("{");
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            sb.append(toString(entry.getKey())).append(": ").append(toString(entry.getValue())).append(", ");
        }
        sb.append("}");
        return sb.toString();
    }

    /** slow! */
    private static Object toString(Object o) {
        return o.getClass().isArray() ? Arrays.toString((Object[]) o) : o.toString();
    }
}

Related

  1. asHexString(ByteBuffer buffer)
  2. asHexString(StringBuilder temp, ByteBuffer buffer)
  3. byteBufferToHex(ByteBuffer buffer)
  4. bytesToHex(ByteBuffer bytes)
  5. bytesToHexString(ByteBuffer b)
  6. toHex(ByteBuffer bb)
  7. toHex(ByteBuffer bb)
  8. toHex(ByteBuffer buf)