aeroxr1
aeroxr1

Reputation: 1074

Android: byte array to decimal string

I have a byte array and I have to print it in a textview, in two differents format : hex string decimal string

For hex string I use this function (found on stackoverflow) :

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

while to convert byte array to decimal string I use this :

   BigInteger bi = new BigInteger(value);

                    // Format to decimal
                    String s = bi.toString(); 

For the byte to hex conversion I am secure that it works correctly, but for the byte-to-decimal string conversion I am no much secure..

Are there better methods ?

EDIT : my desidered output is a decimal value for each byte

Upvotes: 3

Views: 5024

Answers (1)

samgak
samgak

Reputation: 24417

This will print out the byte array as decimals, with leading zeros (as your hex output does) and a space after each number:

final protected static char[] decimalArray = "0123456789".toCharArray();
public static String bytesToDecimal(byte[] bytes) {
    char[] decimalChars = new char[bytes.length * 4];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        decimalChars[j * 4] = decimalArray[v / 100];
        decimalChars[j * 4 + 1] = decimalArray[(v / 10) % 10];
        decimalChars[j * 4 + 2] = decimalArray[v % 10];
        decimalChars[j * 4 + 3] = ' ';
    }
    return new String(decimalChars);
}

I've changed the base from 16 to 10, increased the maximum number of characters from 2 to 3 corresponding to max values of FF for base 16 and 255 for decimal. Modulo 10 is used instead of a binary bitmask for masking individual digits because bitmasks only work with powers of 2 like 16.

Upvotes: 7

Related Questions