Java Byte Array Create toByteArrayV6(String address)

Here you can find the source of toByteArrayV6(String address)

Description

to Byte Array V

License

Open Source License

Parameter

Parameter Description
address a parameter

Return

value

Declaration

private static byte[] toByteArrayV6(String address) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from w w w.ja  v  a2s. com
     * A static array of the hexadecimal digits where their position represents their ordinal value
     */
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**
     * @param address
     * @return value
     */
    private static byte[] toByteArrayV6(String address) {
        String[] tokens = address.split(":");
        byte[] value = new byte[16];
        for (int index = 0; index < value.length; index++) {
            value[index] = 0;
        }

        boolean emptyGroup = false;
        for (int srcIndex = 0, destIndex = 0; destIndex < value.length; srcIndex++, destIndex += 2) {
            if (tokens[srcIndex].length() == 0) {
                emptyGroup = true;
                break;
            }
            int num = hexStringToInt(tokens[srcIndex]);
            value[destIndex] = (byte) (num / 256);
            value[destIndex + 1] = (byte) (num % 256);
        }

        if (emptyGroup) {
            for (int srcIndex = tokens.length - 1, destIndex = 15; destIndex >= 0; srcIndex--, destIndex -= 2) {
                if (tokens[srcIndex].length() == 0) {
                    break;
                }
                int num = hexStringToInt(tokens[srcIndex]);
                value[destIndex] = (byte) (num % 256);
                value[destIndex - 1] = (byte) (num / 256);
            }
        }
        return value;
    }

    /**
     * Converts a hexadecimal string value to the equivalent binary value. Cannot handle more than 8 hex digits.
     * 
     * @param value
     *            The value, expressed as a string of hexadecimal digits (0-F) that are to be converted
     * @return The equivalent binary value
     */
    public static int hexStringToInt(String value) {
        int result = 0;
        for (int position = 0, index = value.length() - 1; index >= 0; index--, position++) {
            char ch = Character.toUpperCase(value.charAt(index));
            for (int i = 0; i < HEX_DIGITS.length; i++) {
                if (HEX_DIGITS[i] == ch) {
                    result += (i * Math.pow(16, position));
                }
            }
        }
        return result;
    }
}

Related

  1. toByteArrays(String s)
  2. toByteArrayShifted(int... arguments)
  3. toByteArrayShifted2(int[][] intArray)
  4. ToByteArrayString(byte[] bytes)
  5. toByteArrayV4(String address)
  6. toByteInfo(long bytes)
  7. toBytes(boolean[] input)
  8. toBytes(byte data)
  9. toBytes(byte[] b, int offset, long val)