gpt-4-1106-preview· OpenAI
WildChat-4.8M (AI2)
java中,字节数组转十六进制字符串怎么做?
- User
java中,字节数组转十六进制字符串怎么做?
- Assistant
在Java中,将字节数组(byte[])转换为十六进制字符串可以通过以下几种方式完成:
- 使用
BigInteger类:
public static String bytesToHex1(byte[] bytes) { BigInteger number = new BigInteger(1, bytes); StringBuilder hexString = new StringBuilder(number.toString(16)); // 需要补齐零(如果表示为十六进制后长度小于字节数组长度的两倍) while (hexString.length() < bytes.length * 2) { hexString.insert(0, '0'); } return hexString.toString(); }- 使用
String.format和StringBuilder:
public static String bytesToHex2(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); }- 使用循环和字符数组:
public static String bytesToHex3(byte[] bytes) { char[] hexArray = "0123456789ABCDEF".toCharArray(); 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); } - 使用
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.