package com.sv.netty.utils;

import java.nio.charset.Charset;

/**
 * USER: douya
 * DATE: 2017-08-28
 */
public class CommonUtils {



    public static byte[] intToBytes2(int n){
        byte[] b = new byte[4];

        for(int i = 0;i < 4;i++)
        {
            b[i]=(byte)(n>>(24-i*8));

        }
        return b;
    }

    /**
     * byte数组转换成16进制字符串
     * @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();
    }

    /**
     * byte数组转换成16进制字符数组
     * @param src
     * @return
     */
    public static String[] bytesToHexStrings(byte[] src){
        if (src == null || src.length <= 0) {
            return null;
        }
        String[] str = new String[src.length];

        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                str[i] = "0";
            }
            str[i] = hv;
        }
        return str;
    }


    public static void  main(String[] arg){
        String message = "{\"cmd\":\"text_message\",\"content\":\"开心开心\",\"member_count\":0,\"system\":0,\"vmc_no\":\"322af403825a\"";
        byte[] bodys = message.getBytes(Charset.forName("UTF-8"));
        String magic = bytesToHexString("doll".getBytes(Charset.forName("UTF-8")));
        String length = bytesToHexString(intToBytes2(bodys.length+8));
        System.out.println(magic+length+bytesToHexString(bodys));
    }

}
