byte array to decimal convertion in java

前端 未结 4 1036
傲寒
傲寒 2020-12-22 03: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

相关标签:
4条回答
  • 2020-12-22 04:38

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

    0 讨论(0)
  • 2020-12-22 04:42

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 04:48

    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;
     }
    
    0 讨论(0)
  • 2020-12-22 04:53

    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 讨论(0)
提交回复
热议问题