Java: byte[] Integer.toHexString()
 
 
 
 
byte[] => hexString
package io.oar; import java.util.Formatter; public class TestByteToHex{ public static void main(String[] args){ byte[] bytes = {-54, -2, -70, -66}; byte b = -54; int i = b >>> 1; // << >> >>> 都会转换成int System.out.println("byteToHex1(bytes) = " + byteToHex1(bytes)); System.out.println("byteToHex2(bytes) = " + byteToHex2(bytes)); System.out.println("byteToHex3(bytes) = " + byteToHex3(bytes)); } public static String byteToHex1(byte[] bytes){ char[] chars = "0123456789ABCDEF".toCharArray(); char[] res = new char[bytes.length * 2]; for(int i = 0; i < bytes.length; i++){ int v = bytes[i] & 0xFF; // byte => int res[2 * i] = chars[v >>> 4]; // byte的前四bits res[2 * i + 1] = chars[v & 0x0F]; // byte的后四bits } return new String(res); } public static String byteToHex2(byte[] bytes){ StringBuilder stringBuilder = new StringBuilder(); for(byte aByte : bytes){ stringBuilder.append(String.format("%02X", aByte)); } return stringBuilder.toString(); } public static String byteToHex3(byte[] bytes){ Formatter formatter = new Formatter(); for(byte aByte : bytes){ formatter.format("%02X", aByte); } String res = formatter.toString(); formatter.close(); return res; } }
                    
                
                
            
        
浙公网安备 33010602011771号