Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer value into 'n' digit ascii byte array in java

Is any method to convert an integer value into 'n' digit ascii byte array in java. Like

IntToBytes( int value, int digits );

int a = 1234;
IntToBytes( a, 4 );
results will be byte array of {1, 2, 3, 4}

IntToBytes( a, 5 );
results will be byte array of {0, 1, 2, 3, 4}

I searched in internet no method found. Please help me

like image 897
Riskhan Avatar asked May 20 '26 21:05

Riskhan


1 Answers

If you want to obtain an array with the values of the digits in decimal notation, you can create a function like this one:

public static byte[] intToBytes(int number, int digits) {
    byte[] results = new byte[digits];
    /* Start at the end of the array. i.e. 1234, should be converted to {1, 2, 3, 4} */
    for (int i = digits - 1; i >= 0; i--) {
        results[i] = (byte) (number % 10);
        number = number / 10;
    }
    return results;
}

If what you want is an array with the ascii value of each digit, you can use String.format and convert the String to the array of bytes.

(1234 should be converted to {'1', '2', '3', '4'}. The ascii values would be {49, 50, 51, 52}

The code could be:

public static byte[] intToBytes(int number, int digits) {
    String format = "%0" + digits + "d";
    String numberAsString = String.format(format, number);
    char[] numberAsCharArray = numberAsString.toCharArray();
    byte[] result = new byte[digits];
    for (int i = 0; i < numberAsCharArray.length; i++) {
        result[i] = (byte) numberAsCharArray[i];
    }
    return result;
}
like image 89
David SN Avatar answered May 23 '26 10:05

David SN