在Java中,你可以使用Integer.toHexString()
方法將整數(shù)轉(zhuǎn)換為其十六進(jìn)制表示形式。然后,你可以使用String.replace()
方法將結(jié)果轉(zhuǎn)換為小寫(如果需要的話)。以下是一個(gè)示例,演示如何將字符串轉(zhuǎn)換為十六進(jìn)制表示形式:
public class BinToHex {
public static void main(String[] args) {
String input = "Hello, World!";
String hexResult = binToHex(input);
System.out.println("Hexadecimal representation: " + hexResult);
}
public static String binToHex(String input) {
// 將輸入字符串轉(zhuǎn)換為其字節(jié)數(shù)組
byte[] inputBytes = input.getBytes();
// 使用Integer.toHexString()方法將字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串
StringBuilder hexBuilder = new StringBuilder();
for (byte b : inputBytes) {
hexBuilder.append(Integer.toHexString(0xff & b));
}
// 刪除每個(gè)十六進(jìn)制字符前的"0x"前綴(如果有的話)
return hexBuilder.toString().toLowerCase();
}
}
這個(gè)示例中的binToHex()
方法接受一個(gè)字符串作為輸入,將其轉(zhuǎn)換為字節(jié)數(shù)組,然后使用Integer.toHexString()
方法將每個(gè)字節(jié)轉(zhuǎn)換為其十六進(jìn)制表示形式。最后,它將結(jié)果轉(zhuǎn)換為小寫并返回。