All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.net.ByteBuffers Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2016 Objectos, Fábrica de Software LTDA.
 *
 * 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.
 */
package br.com.objectos.net;

import java.nio.ByteBuffer;

/**
 * @author [email protected] (Marcio Endo)
 */
public class ByteBuffers {

  private static final char[] hexCode = "0123456789abcdef".toCharArray();
  private static final int hexLimit = 8;

  private ByteBuffers() {
  }

  public static String toHexString(ByteBuffer buffer) {
    int remaining = buffer.remaining();
    StringBuilder r = new StringBuilder(remaining * 2);

    boolean space = true;
    int line = 0;

    buffer.mark();
    while (buffer.hasRemaining()) {
      byte b = buffer.get();

      toHexString(r, b);

      space = !space;

      if (++line == hexLimit) {
        r.append('\n');
        line = 0;
        continue;
      }

      if (space) {
        r.append(' ');
      }
    }
    buffer.reset();

    return r.toString();
  }

  static void toHexString(StringBuilder r, byte b) {
    r.append(hexCode[(b >> 4) & 0xF]);
    r.append(hexCode[(b & 0xF)]);
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy