The Source for Java Technology Collaboration


Home | Help | Changes | Index | Search | Go

ConvertFromByteArrayToInt

Some conversions require two steps to get a value. In this example the intermediate step is to convert the byte array into a String.

/**
 * Input is a byte array with a number in it, such as 0001.
 */
public int convertByteArrayToInt(byte[] theByteArray) {
    String myByteArrayString = new String(theByteArray);
    int myInt = Integer.parseInt(myByteArrayString);
    return myInt;
}
The following is another method used for converting a byte array to an int:

/**
 * Returns an int from a byte array starting at the given offset.
 * This method will convert at most four bytes of the array and
 * maybe less depending on the array length and the given offset.
 *
 * @param array The byte[] from which the bytes are fetched
 * @param offset Integer offset into the array
 * @return A primitive integer data type
 */
public static int byteArrayToInt(byte[] array, int offset)
{
    int j = 0;
    int length = array.length - offset;
    if (length >= 4)
        for (int i=0; i<4; ++i)
            j |= ((int)array[offset+i] & 0xff) << 8*(3-i);
        else
            for (int i=0; i < length; ++i)
                j |= ((int)array[offset+i] & 0xff) << 8*(length-1-i);

        return j;
    }
}

If anyone knows a better way, please change this.



Discussion about ConvertFromByteArrayToInt

These examples are better then the last I commented on. However I feel that the author is assuming that byteArrays always represent a string. This is not really accurate and is probably taken from personal experience the reader is not familiar with. Therefor I repeat my point that I have no idea why this is usefull. The code snippets are not examples, as they don't state a situation where this is usefull. (TZ)

The two routines above don't even do the same thing. One assumes the byte array is made of digits as characters, the other assumes the byte array contains the binary data representing a BigEndian? integer value. The input must be more clearly defined. (SWP)

Topic ConvertFromByteArrayToInt . { Edit | Ref-By | Printable | Diffs r6 < r5 < r4 < r3 < r2 | More }
 XML java.net RSS

Revision r6 - 20 Jul 2003 - 23:28:41 - Main.swpalmer
Parents: WebHome > PossibleArticles > HowTo