0

I want to convert integer to byte[] in java. And I did some research and found the code

    public byte[] integerToBytes (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;
    }

I'm pretty sure the code is right cause it passes the tests. However, I'm a little bit confused.

Suppose the integer is 36666666. And binary representation is 10001011110111110100101010.I can understand why it is true for result[0] since after the shift, it becomes 10001011(0x22).However,for result[1],after the shift,it becomes 1000101111011111(0x22F7).

But what I really want is just 0xF7.

Can someone explain this to me or I understand this code in a wrong way?

Cheers

1 Answer 1

3

The reason result[1] and others are just the lowest eight bits is due to the the cast to a byte performed on each assignment. Casting an int like 0x22F7 to a byte cuts off the top 3 bytes and leaves the least significant byte to be assigned to the new variable. Thus 0x22f7 becomes just 0xf7. Hope this helps.

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.