byte array to decimal convertion in java

早过忘川 提交于 2019-12-18 09:26:34

问题


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



来源:https://stackoverflow.com/questions/3149058/byte-array-to-decimal-convertion-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!