NRaj
NRaj

Reputation: 121

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

Upvotes: 0

Views: 582

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19565

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

Upvotes: 1

WJS
WJS

Reputation: 40062

Try this. It works by:

  • streaming the indices of the byte array
  • maping to an int and getting rid of the sign extension
  • reducing to a long by shift and or operations.
byte[] bytes = { -112, 21, 64, 0, 7, 50, 54, 127 };

long lng = IntStream.range(0, bytes.length)
        .mapToLong(i -> bytes[i] & 0xff)
        .reduce(0L, (a, b) -> (a << 8) | b);

System.out.println("long decimal value = " + lng);
System.out.println("long hex value = " + Long.toHexString(lng));    

prints

long decimal value = -8064469188872096129
long hex value = 901540000732367f

Using the same technique, the other example of {49, 55, 48, 51, 55} should be:

long decimal value = 211379303223
long hex value = 3137303337

Upvotes: 1

Related Questions