Java ByteBuffer to Hex toHex(ByteBuffer buffer)

Here you can find the source of toHex(ByteBuffer buffer)

Description

to Hex

License

Open Source License

Declaration

public static String toHex(ByteBuffer buffer) 

Method Source Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    static final String HEX = "0123456789ABCDEF";

    public static String toHex(ByteBuffer buffer) {
        StringBuilder result = new StringBuilder();
        int pos = buffer.position();
        buffer.position(0);/*  w  w w.ja v  a2s.  co m*/

        for (int i = buffer.limit(); --i >= 0;) {
            byte b = buffer.get();
            result.append(HEX.charAt((b >> 4) & 0xF));
            result.append(HEX.charAt(b & 0xF));
            result.append(' ');
        }

        buffer.position(pos);

        return result.toString();
    }

    public static String toHex(byte[] buffer) {
        StringBuilder result = new StringBuilder();

        for (byte b : buffer) {
            result.append(HEX.charAt((b >> 4) & 0xF));
            result.append(HEX.charAt(b & 0xF));
            result.append(' ');
        }

        return result.toString();
    }

    static void append(ByteBuffer buffer, String s) {
        int len = s.length();
        for (int i = 0; i < len; i++)
            buffer.put((byte) s.charAt(i));
        buffer.put((byte) 0);
        align(buffer);
    }

    static void append(ByteBuffer buffer, byte[] data) {
        buffer.putInt(data.length);
        buffer.put(data);
        align(buffer);
    }

    static void append(ByteBuffer buffer, Object o) {
        if (o instanceof Integer) {
            buffer.putInt((Integer) o);
        } else if (o instanceof Float) {
            buffer.putFloat((Float) o);
        } else if (o instanceof Double) {
            buffer.putDouble((Double) o);
        } else if (o instanceof String) {
            append(buffer, (String) o);
        } else if (o instanceof byte[]) {
            append(buffer, (byte[]) o);
        } else if (o instanceof Boolean) {
            // Nothing to do. The value (true or false) is already sent in the
            // type string
        } else if (o == null) {
            // Nothing to do. The type string alreday specifies a null
        } else
            throw new IllegalArgumentException("Unsupported OSC Type:" + o.getClass().getName());
    }

    static void align(ByteBuffer buffer) {
        buffer.position(((buffer.position() + 3) / 4) * 4);
    }
}

Related

  1. bytesToHex(ByteBuffer bytes)
  2. bytesToHexString(ByteBuffer b)
  3. toHex(ByteBuffer bb)
  4. toHex(ByteBuffer bb)
  5. toHex(ByteBuffer buf)
  6. toHex(ByteBuffer data)
  7. toHexStr(final ByteBuffer data)
  8. toHexStream(ByteBuffer data)
  9. toHexString(ByteBuffer bb)