Ví dụ 1: Chuyển 12 sang chuỗi byte array và ngược lại
package com.mycompany;
public class ConvertIntBytes {
public static void main(String[] args) {
ConvertIntBytes bytes = new ConvertIntBytes();
byte[] byteArray = bytes.InttoBytes(12);
for (byte b : byteArray) {
System.err.println("b " + b);
}
int x = bytes.ByteToInt(byteArray);
System.err.println("x :" + x);
}
// hàm chuyển int sang chuổi bayte 4 bit
public byte[] InttoBytes(int i) {
byte[] result = new byte[4];
result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);
return result;
}
// hàm chuyển chuỗi bay sang int
public int ByteToInt(byte[] bytes) {
int x = 0;
try {
x = java.nio.ByteBuffer.wrap(bytes).getInt();
} catch (Exception e) {
System.err.println("Error " + e);
}
return x;
}
// hàm chuyển chuỗi byte sang int cách khác
public int byteArrayToInt(byte[] b, int lengthByte) {
int value = 0;
for (int i = 0; i < lengthByte; i++) {
int shift = (lengthByte - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
}
Output:
b 0
b 0
b 0
b 12
x :12