byte array to decimal convertion in java

2019-01-29 04:59发布

问题:

I am new to java. I receive the UDP data in byte array. Each elements of the byte array have the hexadecimal value. I need to convert each element to integer.

How to convert it to integer?

回答1:

sample code:

 public int[] bytearray2intarray(byte[] barray)
 {
   int[] iarray = new int[barray.length];
   int i = 0;
   for (byte b : barray)
       iarray[i++] = b & 0xff;
   // "and" with 0xff since bytes are signed in java
   return iarray;
 }


回答2:

Manually: Iterate over the elements of the array and cast them to int or use Integer.valueOf() to create integer objects.



回答3:

Function : return unsigned value of byte array.

public static long bytesToDec(byte[] byteArray) {
    long total = 0;
    for(int i = 0 ; i < byteArray.length ; i++) {
        int temp = byteArray[i];
        if(temp < 0) {
            total += (128 + (byteArray[i] & 0x7f)) * Math.pow(2, (byteArray-1-i)*8); 
        } else {
            total += ((byteArray[i] & 0x7f) * Math.pow(2, (byteArray-1-i)*8));
        }
    }
    return total;
}


回答4:

Here's something I found that may be of use to you http://blog.codebeach.com/2008/02/convert-hex-string-to-integer-and-back.html