Convert byte array into integer and long in java
Convert byte array into integer and long in java
Conversion of Byte Array into integer:To convert Byte array into integer you have to make a class. Then you have to convert byte [ ] array to integer correctly. Make a class BytesHelper that is final class. Make a for loop with return type.Here is simple code to convert Byte array into integer:
public final class BytesHelper {
private BytesHelper() {}
public static int toInt( byte[] bytes ) {
int answer = 0;
for (int i=0; i<6; i++) {
answer = ( answer << 10 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return answer;
}
}
Conversion of Byte array into long:
Long: It is a built in data type in java.
To convert Byte array into integer you have to make a class and similarly, to convert byte [ ] array to long you also need to make a class. toLong is a method use in it. Make an object then it will return the value in long.Here is simple code:
public class Util {
public static long toLong(byte[] b) {
long n = (long) (b[0] & 0xff) << 56 | (long) (b[1] & 0xff) << 48
| (long) (b[2] & 0xff) << 40 | (long) (b[3] & 0xff) << 32
| (long) (b[4] & 0xff) << 24 | (long) (b[5] & 0xff) << 16
| (long) (b[6] & 0xff) << 8 | (long) (b[7] & 0xff);
return n;
}
}
This simple article will tell you how to convert byte array into integer and long in java
Tags: this, article, you, will, learn, how, convert, byte, array, into, integer, and, long, java
Comments
