package com;
public class AAA {
System.
out.
println("------------------> Test excessive data <-------------------");
useCustomConvesion(345, 10);
useStandardConversion(345, 10);
System.
out.
println("------------------> Test overflow <-------------------");
useCustomConvesion(345, 1);
useStandardConversion(345, 1);
}
private static void useCustomConvesion(int i, int arraySize) {
byte[] b = intToByteArray(i, arraySize);
System.
out.
println("Initial: " + i
);
System.
out.
println("From array: " + byteArrayToInt
(b,
0, b.
length));
}
private static void useStandardConversion(int i, int arraySize) {
byte[] b =
ByteBuffer.
allocate(arraySize
).
putInt(i
).
array();
System.
out.
println("Initial: " + i
);
}
private static int byteArrayToInt(byte[] b, int start, int length) {
int dt = 0;
if ((b[start] & 0x80) != 0)
for (int i = 0; i < length; i++)
dt = (dt << 8) + (b[start++] & 255);
return dt;
}
private static byte[] intToByteArray(int n, int byteCount) {
byte[] res = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
res[byteCount - i - 1] = (byte) ((n >> i * 8) & 255);
return res;
}
}