user2634966 user2634966 - 1 year ago 242
Android Question

Convert integer to unsigned byte array with java or android

Hi i have seen many links in SO to convert integer value to unsigned byte array. but i can't able to get clear idea. my conversion is as follows

//in android

int checksum=104396;

byte[] byteArray = GetBytesInt(checksum);

public static byte[] GetBytesInt(int value) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (value >> 24);
bytes[1] = (byte) (value >> 16);
bytes[2] = (byte) (value >> 8);
bytes[3] = (byte) (value);
return bytes;

Output in android


//in c#

uint CheckSum=104396;

byte[] byteArray=BitConverter.GetBytes(CheckSum)

where BitConverter is System method

output in c#


How i get this output in java or android. I check java 8 and Guava there are returning the same.

please help me with some coding

Answer Source

As per @greenapps suggestion, Getting byte array in LITTLE_ENDIAN format solved the problem.

ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.putInt((int) (value & 0xffffffffL));
byte[] array=Bytes.asList(byteBuffer.array())

Output in android


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download