Reputation: 29411
I have a list of Integer
List<Integer> listInt;
I want to generate a MD5 hash for the listInt how should I approach the problem, I know that I have to use
MessageDigest.getInstance("MD5").digest(byte[])
How do I convert the listInt to bytes.
Upvotes: 1
Views: 3785
Reputation: 39218
You need to convert each integer value to 4 bytes, forming an array of bytes that is 4*listInt.size()
bytes long.
One way to do this is to make use of NIO's ByteBuffer class:
ByteBuffer buf = ByteBuffer.allocate(4*listInt.size());
buf.order(ByteOrder.BIG_ENDIAN);
for (int i = 0; i < listInt.size(); ++i)
buf.putInt(listInt.get(i));
byte[] barr = buf.array();
Note that there are two common ways of converting an array of integers to an array of bytes. The difference, however, is simply the choice of Endianness. Some people choose to calculate the Big Endian byte representation of integers; others choose to calculate the little Endian representation of integers. It doesn't matter which method you pick as long as you calculate the byte representation of each integer consistently.
Upvotes: 2
Reputation: 22168
First create a method that converts an int to a byte array:
public static final byte[] intToByteArray(int value)
{
return new byte[] { (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
}
Then use a ByteArrayOutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < listInt.size(); i++)
{
baos.write(intToByteArray(listInt[i]), 0, 4);
}
You will then get your full byte array to perform the md5 hash on by:
byte[] fullByteArray = baos.toByteArray();
Upvotes: 1
Reputation: 138417
byte data[] = new byte[listInt.size()*4];
for (int i = 0; i < listInt.size(); i++) {
data[i*4] = new Integer(listInt.get(i) >> 24).byteValue();
data[i*4+1] = new Integer(listInt.get(i) >> 16).byteValue();
data[i*4+2] = new Integer(listInt.get(i) >> 8).byteValue();
data[i*4+3] = listInt.get(i).byteValue();
}
Sample code running: http://ideone.com/YJZVj
Upvotes: 1