Byte array before decimal conversion in java

I am new to java. I get UDP data in an array of bytes. Each element of the byte array has a hexadecimal value. I need to convert each element to an integer.

How to convert it to an integer?

+1
source share
4 answers

code example:

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

Manually: go through the elements of the array and add them to int or use Integer.valueOf() to create whole objects.

+2
source

Function: returns an unsigned 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; } 
+1
source

Here's something I found that might come in handy to you http://blog.codebeach.com/2008/02/convert-hex-string-to-integer-and-back.html

0
source

Source: https://habr.com/ru/post/945927/


All Articles