package com.xydl.cac.util;

import java.io.IOException;
import java.math.BigInteger;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.util.StringUtils;

public class ByteUtil {
    public static byte[] uintToBytes(long value) {
        byte[] src = new byte[4];
        src[3] = ((byte) (int) (value >> 24 & 0xFF));
        src[2] = ((byte) (int) (value >> 16 & 0xFF));
        src[1] = ((byte) (int) (value >> 8 & 0xFF));
        src[0] = ((byte) (int) (value & 0xFF));
        return src;
    }

    public static byte[] uint16ToBytes(int value) {
        byte[] src = new byte[2];
        src[1] = ((byte) (value >> 8 & 0xFF));
        src[0] = ((byte) (value & 0xFF));
        return src;
    }

    public static byte[] uint8ToBytes(short value) {
        byte[] src = new byte[1];
        src[0] = ((byte) (value & 0xFF));
        return src;
    }

    /**
     * ascii 转 十六进制
     *
     * @param str
     * @return
     */
    public static String convertStringToHex(String str) {

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((int) chars[i]));
        }

        return hex.toString();
    }

    /**
     * 十六进制转 ascii
     *
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        // 49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            // grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            // convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            // convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    /**
     * 十六进制字符串高低位互换
     * <p>
     * 如：12345678 -> 78563412
     * 00 5f 8d c2
     * c28d5f00
     *
     * @param str
     * @return float
     */
    public static float hexStrTofloat(String str) {
        try {
            String s = str.substring(6, 8) + str.substring(4, 6) + str.substring(2, 4) + str.substring(0, 2);
            return Float.intBitsToFloat(new BigInteger(s, 16).intValue());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            System.err.println("errrrr..");
            return 0L;
        }
    }

    public static float hexStrTofloat1(String str) {
        try {
            int i = Integer.parseInt(str, 16);
            byte byte4 = (byte) (i & 0xff);
            byte byte3 = (byte) ((i & 0xff00) >> 8);
            byte byte2 = (byte) ((i & 0xff0000) >> 16);
            byte byte1 = (byte) ((i & 0xff000000) >> 24); // 拼装成 "高字节在后，低字节在前"的格式
            int realint = (byte1 & 0xff) << 0 | (byte2 & 0xff) << 8 | (byte3 & 0xff) << 16 | (byte4 & 0xff) << 24;
            return Float.intBitsToFloat(realint);
        } catch (NumberFormatException e) {
            System.err.println("errrrr..");
            return 0L;
        }

    }

    public static int bytesToInt(byte[] src, int startPos) {
        if ((src == null) || (src.length <= 0) || (src.length < startPos + 4) || (startPos < 0)) {
            return -1;
        }
        int result = (int) ((src[(startPos + 3)] & 0xFF) * 16777216 + (src[(startPos + 2)] & 0xFF) * 65536L
                + (src[(startPos + 1)] & 0xFF) * 256L + (src[startPos] & 0xFF));
        return result;
    }

    public static int bytesToIntHL(byte[] src, int startPos, int len) {
        if ((src == null) || (src.length <= 0) || (src.length < startPos + len) || (startPos < 0)) {
            return -1;
        }
        int result = 0;
        for (int i = 0; i < len; i++) {
            result += (int) ((src[(startPos + i)] & 0xFF) * (1 << (len - 1 - i) * 8));
        }
        return result;
    }

    public static void printHexString(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase() + " ");
        }
        System.out.println();
    }

    /**
     * 字节数组转为十六进制字符串
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String bytesToDecString(byte[] src) {
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        int result = (int) ((src[3] & 0xFF) * 16777216 + (src[2] & 0xFF) * 65536L + (src[1] & 0xFF) * 256L
                + (src[0] & 0xFF));
        return Integer.toString(result);
    }

    public static String bytesToHexString(byte[] src, int len) {
        StringBuilder stringBuilder = new StringBuilder("");
        StringBuilder temp = new StringBuilder("");
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            if (v != 0) {
                String hv = Integer.toHexString(v);
                StringBuilder temp1 = new StringBuilder("");
                if (hv.length() < 2) {
                    temp1.append(0);
                }
                temp1.append(hv);
                temp1.append(temp);
                temp = temp1;
            }
        }
        if (len / 2 > temp.length()) {
            String result = temp.toString();
            for (int k = 0; k < (len - result.length()) / 2; k++) {
                stringBuilder.append("00");
            }
            stringBuilder.append(result);
        } else {
            stringBuilder = temp;
        }
        return stringBuilder.toString();
    }

    public static String bytesToDecString(byte[] src, int len) {
        if ((src == null) || (src.length <= 0)) {
            return null;
        }
        int result = (int) (src[3] * 16777216 + src[2] * 65536L + src[1] * 256L + src[0]);
        String temp = Integer.toString(result);
        if (temp.length() < len) {
            StringBuilder finalString = new StringBuilder("");
            for (int k = 0; k < len - temp.length(); k++) {
                finalString.append(0);
            }
            finalString.append(result);
            return finalString.toString();
        }
        return temp;
    }

    public static float byte2float(byte[] b, int index) {
        int l = b[(index + 0)];
        l &= 0xFF;
        l = (int) (l | b[(index + 1)] << 8);
        l &= 0xFFFF;
        l = (int) (l | b[(index + 2)] << 16);
        l &= 0xFFFFFF;
        l = (int) (l | b[(index + 3)] << 24);
        return Float.intBitsToFloat(l);
    }

    public static int ASCIIToInt(byte[] b, int len) {
        int result = 0;
        for (int i = 0; i < len; i++) {
            char temp = (char) b[i];
            int i_temp;
            switch (temp) {
                case 'A':
                    i_temp = 10;
                    break;
                case 'B':
                    i_temp = 11;
                    break;
                case 'C':
                    i_temp = 12;
                    break;
                case 'D':
                    i_temp = 13;
                    break;
                case 'E':
                    i_temp = 14;
                    break;
                case 'F':
                    i_temp = 15;
                    break;
                default:
                    i_temp = Integer.valueOf(temp).intValue();
            }
            result = i_temp + result * 16;
        }
        return result;
    }

    public static String ASCIIToString(byte[] b, int len) {
        String result = "";
        for (int i = 0; i < len; i++) {
            result = result + (char) b[i];
        }
        return result;
    }


    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if (str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }


    /**
     * 带符号的16进制字符串转float
     */
    public static float SigneHexToFloat(String str) {
        String s = str.substring(2, 4) + str.substring(0, 2);
        float x = (float) Integer.valueOf(s, 16).shortValue();
        return x;
    }

    /**
     * 有符号16进制转10进制
     *
     * @param strHex
     * @return
     */
    public static int signedHexToDec(String strHex) {
        if (strHex.length() == 0) {
            return 0;
        }
        int x = 0;
        //带符号十六进制转换十进制
        String fristNum = strHex.substring(0, 1);
        String hexStr2Byte = parseHexStr2Byte(fristNum);
        String flag = hexStr2Byte.substring(0, 1);
        if ("1".equals(flag)) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < strHex.length(); i++) {
                String num = strHex.substring(i, i + 1);
                int decNum = Integer.parseInt(num, 16);
                int a = decNum ^ 15;
                sb.append(intToHex(a));
            }
            x = -Integer.parseInt(sb.toString(), 16) - 1;
        } else {
            x = Integer.parseInt(strHex, 16);
        }

        return x;

    }

    //十进制转16进制
    private static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        return a;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static String parseHexStr2Byte(String hexStr) {
        if (hexStr.length() == 0) {
            return null;
        }
        int sint = Integer.valueOf(hexStr, 16);
        //十进制在转换成二进制的字符串形式输出!
        String bin = Integer.toBinaryString(sint);
        for (int i = bin.length(); i < 4; i++) {
            bin = "0" + bin;
        }
        return bin;
    }
}

