Java code To convert byte to Hexadecimal

后端 未结 19 2516
我寻月下人不归
我寻月下人不归 2020-11-22 17:26

I have an array of bytes. I want each byte String of that array to be converted to its corresponding hexadecimal values.

Is there any function in Java to convert a b

19条回答
  •  情书的邮戳
    2020-11-22 17:47

    I couldn't figure out what exactly you meant by byte String, but here are some conversions from byte to String and vice versa, of course there is a lot more on the official documentations

    Integer intValue = 149;
    

    The corresponding byte value is:

    Byte byteValue = intValue.byteValue(); // this will convert the rightmost byte of the intValue to byte, because Byte is an 8 bit object and Integer is at least 16 bit, and it will give you a signed number in this case -107
    

    get the integer value back from a Byte variable:

    Integer anInt = byteValue.intValue(); // This will convert the byteValue variable to a signed Integer
    

    From Byte and Integer to hex String:
    This is the way I do it:

    Integer anInt = 149
    Byte aByte = anInt.byteValue();
    
    String hexFromInt = "".format("0x%x", anInt); // This will output 0x95
    String hexFromByte = "".format("0x%x", aByte); // This will output 0x95
    

    Converting an array of bytes to a hex string:
    As far as I know there is no simple function to convert all the elements inside an array of some Object to elements of another Object, So you have to do it yourself. You can use the following functions:

    From byte[] to String:

        public static String byteArrayToHexString(byte[] byteArray){
            String hexString = "";
    
            for(int i = 0; i < byteArray.length; i++){
                String thisByte = "".format("%x", byteArray[i]);
                hexString += thisByte;
            }
    
            return hexString;
        }
    

    And from hex string to byte[]:

    public static byte[] hexStringToByteArray(String hexString){
        byte[] bytes = new byte[hexString.length() / 2];
    
        for(int i = 0; i < hexString.length(); i += 2){
            String sub = hexString.substring(i, i + 2);
            Integer intVal = Integer.parseInt(sub, 16);
            bytes[i / 2] = intVal.byteValue();
            String hex = "".format("0x%x", bytes[i / 2]);
        }
    
        return bytes;
    }  
    

    It is too late but I hope this could help some others ;)

提交回复
热议问题