Search code examples
javaarraysasciisigned

How to convert signed byte array to ascii in Java


In Java program I have signed byte array as

[-112, 21, 64, 0, 7, 50, 54, 127]

how i can convert into ascii number which is equal to

901540000732367F

Solution

  • It seems that the order of bytes in the result is reverse to that of the array, so you should iterate the array in the reverse order and add each element with a shift by the predefined number of bits:

    private static String convertToHexFullByte(byte[] arr) {
        return convertToHex(arr, 8);
    }
        
    private static String convertToHexHalfByte(byte[] arr) {
        return convertToHex(arr, 4);
    }
        
    private static String convertToHex(byte[] arr, int bits) {
        long mask = 0;
        for (int i = 0; i < bits; i++) {
            mask |= 1 << i;
        }
        long res = 0;
        for (int i = arr.length - 1, j = 0; i >= 0; i--, j += bits) {
            res |= (arr[i] & mask) << j;
        }
    
        return Long.toHexString(res).toUpperCase();        
    }
    

    Test

    public static void main(String args[]) {
        byte[] arr4 = {49, 55, 48, 51, 55};
            
        System.out.println(convertToHexHalfByte(arr4));
            
        byte[] arr8 = {-112, 21, 64, 0, 7, 50, 54, 127};
            
        System.out.println(convertToHexFullByte(arr8));
    }
    

    output

    17037
    901540000732367F