English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将字节数组转换为十六进制

Java Comprehensive Examples

在此程序中,您将学习在Java中将字节数组转换为十六进制的不同方法。

示例1:将字节数组转换为十六进制值

public class ByteHex {
    public static void main(String[] args) {
        byte[] bytes = {10, 2, 15, 11};
        for (byte b : bytes) {
            String st = String.format("%02X", b);
            System.out.print(st);
        }
    }
}

运行该程序时,输出为:

0A020F0B

在上面的程序中,我们有一个名为bytes的字节数组。要将字节数组转换为十六进制值,我们遍历数组中的每个字节并使用String的format()。

我们使用%02X打印十六进制(X)值的两个位置(02),并将其存储在字符串st中。

对于大字节数组转换,这是相对较慢的过程。我们可以使用下面显示的字节操作大大提高执行速度。

示例2:使用字节操作将字节数组转换为十六进制值

public class ByteHex {
    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();}}
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    public static void main(String[] args) {
        byte[] bytes = {10, 2, 15, 11};
        String s = bytesToHex(bytes);
        System.out.println(s);
    }
}

The output of this program is consistent with the example1The same.

Java Comprehensive Examples