1

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
[0,1,-105,-52]

//in c#

uint CheckSum=104396;

byte[] byteArray=BitConverter.GetBytes(CheckSum)

where BitConverter is System method

output in c#

[204,151,1,0]

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

4
  • Output in android. You did not post the code that outputs. Commented Oct 13, 2016 at 9:27
  • i mentioned the op byte value below the code Commented Oct 13, 2016 at 9:29
  • No. I saw the output already of course. But i asked for the code you used to produce the output. How did you print them? Commented Oct 13, 2016 at 9:30
  • 1
    You see that the result is ok? Java and C# produce equal results. Add 256 to negative values in Android. Only the sequence is different. You should consider each byte value as unsigned when printing. Commented Oct 13, 2016 at 9:36

1 Answer 1

0

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

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

Output in android

[-52,-105,1,0]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.