搜索
您的当前位置:首页正文

16进制转换byte数组;byte数组转16进制;随机产生一组16进制数;读写

来源:易榕旅网
将byte数组转换为16进制数:
    public static final char[] HEX = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes, int length) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < Math.min(length, bytes.length); j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX[v >>> 4];
            hexChars[j * 2 + 1] = HEX[v & 0x0F];
        }
        return new String(hexChars);
    }
将16进制数转换为byte数组:
    public static byte[] hex2Byte(String hex) {
        String[] parts = hex.split(" ");
        byte[] bytes = new byte[parts.length];
        for (int i = 0; i < parts.length; i++) {
            bytes[i] = (byte) Integer.parseInt(parts[i], 16);
        }
        return bytes;
    }
随机产生一组16进制数
    public static String randomHexString(int length) {
        StringBuffer result = new StringBuffer();
        Random random = new Random();
        try {
            for (int i = 0; i < length; i++) {
                String hexString = Integer.toHexString(random.nextInt(255));
                if (hexString.length() == 1) {
                    result.append("0");
                }
                result.append(hexString).append(" ");
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
插入到最后一个byte数据
    public static byte[] insertTail(byte[] arr, byte value) {
        if (arr == null) {
            return null;
        }
        arr = Arrays.copyOf(arr, arr.length + 1);
        arr[arr.length - 1] = value;
        return arr;
    }
按行读取文件:
    private static String read(File file) {
        if (file == null || !file.exists()) {
            return null;
        }

        StringBuilder builder = new StringBuilder();

        Scanner scanner;
        try {
            scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                builder.append(scanner.nextLine()).append('\n');
            }
            builder.deleteCharAt(builder.length() - 1);
        } catch (FileNotFoundException e) {
            return null;
        }

        if (scanner != null) {
            scanner.close();
        }

        return builder.toString();
    }
按字符写入文件:
    public static void write(File file, String content) {
        if (file == null) {
            return;
        }

        FileWriter writer;
        try {
            writer = new FileWriter(file);

            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            return;
        }

        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

因篇幅问题不能全部显示,请点此查看更多更全内容

Top