开发者

byte array to decimal convertion in java

开发者 https://www.devze.com 2023-01-05 18:17 出处:网络
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.

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?


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;
 }


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


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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消