Java Hex Calculate toHex(byte[] address, StringBuilder builder)

Here you can find the source of toHex(byte[] address, StringBuilder builder)

Description

to Hex

License

Apache License

Declaration

public static void toHex(byte[] address, StringBuilder builder) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {

    public static String toHex(byte[] address) {
        StringBuilder builder = new StringBuilder();
        toHex(address, builder);//from   ww  w. jav a 2s .c  o m
        return builder.toString();
    }

    public static void toHex(byte[] address, StringBuilder builder) {
        if (address == null || address.length < 4) {
            throw new IllegalArgumentException("address is invalid");
        }
        if (builder == null) {
            throw new IllegalArgumentException("builder is invalid");
        }
        String hex;
        int pos = 0;
        int port = 0;
        if (address.length >= 6) {
            port = address[pos++] & 0xFF;
            port |= (address[pos++] << 8 & 0xFF00);
        }

        for (int i = 0; i < 4; i++) {
            hex = Integer.toHexString(address[pos++] & 0xFF).toUpperCase();
            if (hex.length() == 1) {
                builder.append('0').append(hex);
            } else {
                builder.append(hex);
            }
        }
        if (address.length >= 6) {
            hex = Integer.toHexString(port).toUpperCase();
            int len = hex.length();
            if (len == 1) {
                builder.append("000").append(hex);
            } else if (len == 2) {
                builder.append("00").append(hex);
            } else if (len == 3) {
                builder.append("0").append(hex);
            } else {
                builder.append(hex);
            }
        }
    }
}

Related

  1. toHex(byte value)
  2. toHex(byte value)
  3. toHex(byte... bs)
  4. toHex(byte... bytes)
  5. toHex(byte[] a)
  6. tohex(byte[] arg)
  7. toHex(byte[] arr)
  8. toHex(byte[] array)
  9. toHex(byte[] array, int offset, int length)