package com.uavps.framework.udp.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class BytesUtils {

    /**
     * int shor 类型转byte[]
     *
     * @param object 被转对象
     * @param len 数组长度
     * @return 输出对应长度字节数组
     */
    public static byte[] getBytes(Object object, int len) {
        ByteBuffer buffer = ByteBuffer.allocate(len);
        if (object instanceof Integer) {
            // 使用ByteBuffer将int转为byte数组
            buffer.putInt((Integer) object);
        } else if (object instanceof Short) {
            // 使用ByteBuffer将Short转为byte数组
            buffer.putShort((Short) object);
        }
        return buffer.array();
    }

    public static String toHexString(Object object, int len) {
        byte[] bytes = getBytes(object, len);
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    public static String intToHex(int num, int paddingLength) {
//        String hex = Integer.toHexString(num);
        String hex = intToHexLittleEndianNoPadding(num);
        // 补零到指定位数
        while (hex.length() < paddingLength) {
            hex = hex + "0";
        }
        return hex;
    }

    public static String intToHexLittleEndianNoPadding(int value) {
        byte[] bytes = ByteBuffer.allocate(4)
                .order(ByteOrder.LITTLE_ENDIAN)
                .putInt(value)
                .array();

        // 找到最后一个非零字节的位置
        int lastNonZeroIndex = bytes.length - 1;
        while (lastNonZeroIndex >= 0 && bytes[lastNonZeroIndex] == 0) {
            lastNonZeroIndex--;
        }

        // 如果没有非零字节（value=0），返回 "00"
        if (lastNonZeroIndex < 0) {
            return "00";
        }

        // 只保留非零部分
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i <= lastNonZeroIndex; i++) {
            hexString.append(String.format("%02x", bytes[i]));
        }

        return hexString.toString();
    }
}
