Java ByteBuffer to Hex toHexString(ByteBuffer byteBuffer)

Here you can find the source of toHexString(ByteBuffer byteBuffer)

Description

Encodes a byte buffer into hex (no spaces) string from the current position.

License

Open Source License

Parameter

Parameter Description
byteBuffer a parameter

Declaration

public static String toHexString(ByteBuffer byteBuffer) 

Method Source Code

//package com.java2s;
/**/*from  w  w  w  . j av a2  s.  c  om*/
 * Created on June 29, 2009.
 *
 * Copyright 2010- The MITRE Corporation. All rights reserved.
 *
 * 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 andlimitations under
 * the License.
 *
 * $Id$
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Encodes a byte buffer into hex (no spaces) string from the current position.
     *
     * This preserves the current position of the {@link ByteBuffer}.
     * @param byteBuffer
     * @return
     */
    public static String toHexString(ByteBuffer byteBuffer) {
        if (byteBuffer == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        int pos = byteBuffer.position();
        //byteBuffer.rewind();
        while (byteBuffer.hasRemaining()) {
            String hex = Integer.toHexString(0xFF & byteBuffer.get());
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex);
        }
        byteBuffer.position(pos);
        return sb.toString();
    }
}

Related

  1. toHexString(ByteBuffer bb)
  2. toHexString(ByteBuffer bb, boolean withSpaces)
  3. toHexString(ByteBuffer buffer)
  4. toHexString(ByteBuffer buffer)
  5. toHexString(ByteBuffer buffer, int size)
  6. toHexString(ByteBuffer byteBuffer)
  7. toHexString(final ByteBuffer buffer)
  8. toHexValue(ByteBuffer buffer)