Java Hex Format formatAddress6(int[] hexRepresentation)

Here you can find the source of formatAddress6(int[] hexRepresentation)

Description

Converts IPV6 int[] representation into valid IPV6 string literal.

License

Apache License

Parameter

Parameter Description
hexRepresentation a parameter

Declaration

private static String formatAddress6(int[] hexRepresentation) 

Method Source Code

//package com.java2s;
/*//from w  ww. jav  a  2 s  .  c  om
 * Copyright 2016 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.
 */

public class Main {
    private static final int IPV6_LEN = 8;

    /**
     * Converts IPV6 int[] representation into valid IPV6 string literal. Sequence of '-1' values are converted into '::'.
     * @param hexRepresentation
     * @return
     */
    private static String formatAddress6(int[] hexRepresentation) {
        if (hexRepresentation == null) {
            throw new NullPointerException();
        }
        if (hexRepresentation.length != IPV6_LEN) {
            throw new IllegalArgumentException();
        }
        StringBuilder stringBuilder = new StringBuilder();
        boolean inCompressedSection = false;
        for (int i = 0; i < hexRepresentation.length; i++) {
            if (hexRepresentation[i] == -1) {
                if (!inCompressedSection) {
                    inCompressedSection = true;
                    if (i == 0) {
                        stringBuilder.append("::");
                    } else {
                        stringBuilder.append(':');
                    }
                }
            } else {
                inCompressedSection = false;
                stringBuilder.append(Integer
                        .toHexString(hexRepresentation[i]));
                if (i + 1 < hexRepresentation.length) {
                    stringBuilder.append(":");
                }
            }
        }
        return stringBuilder.toString();
    }
}

Related

  1. FormatAs2CharHexa(byte byValue)
  2. FormatAs4CharHexa(int nValue)
  3. formatAsHex(byte[] bytes)
  4. formatAsHex(long msgId)