Rohan Keskar
Rohan Keskar

Reputation: 79

How to convert uint8 byte array to string in Java

I have an unint8 byte array which a function from a library is returning the library is cross compiled from golang using gomobile, Golang has byte arrays of type unint8,

The byte array is

[4, 19, 35, 76, -77, -6, 106, -70, -95, -37, -58, 2, 20, 94, 34, -73, 79, 69, -84, -90, 30, 27, 125, -102, -116, 105, 52, 89, -62, 116, -92, 27, -56, 98, -124, 42, -2, -109, -30, -101, -60, -12, -103, 28, 26, 46, -54, -33, 61, -17, 115, 39, -14, -15, -60, -109, -119, -106, -128, 95, 65, 84, 12, -56, -76]

I want to convert this byte array to string in java

I know you can convert byte to string using new String()

but when I convert the byte array I get random characters as

♦‼#L��j����☻¶^\"�OE��▲��i4Y�t�b�*�����∟→.��=�s'��ē���_AT♀ȴ

Upvotes: 1

Views: 859

Answers (1)

Christopher
Christopher

Reputation: 10269

I am not sure, what is your expected output. This function would print out something like:

010203041B1A

public class ByteUtils {

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static final int MASK_BYTE_SIZE = 0xFF;
private static final int MASK_SECOND_TUPLE = 0x0F;
private static final int SHIFT_FIRST_TUPLE = 4;

public static String bytesToHexString(final byte... bytes) {
    if (bytes == null || bytes.length == 0) {
        return "";
    }
    final char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & MASK_BYTE_SIZE;
        hexChars[j * 2] = HEX_ARRAY[v >>> SHIFT_FIRST_TUPLE];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & MASK_SECOND_TUPLE];
    }
    return new String(hexChars);
}
}

Upvotes: 1

Related Questions