0

I encountered this way of encoding an integer to bytes String

  public String intToString(int x) {
    char[] bytes = new char[4];
    for(int i = 3; i > -1; --i) {
      bytes[3 - i] = (char) (x >> (i * 8) & 0xff);
    }
    return new String(bytes);
  }

I didn't quite understand why do we iterate in this order

(x >> (24) & 0xff);  //stored in bytes[0]
(x >> (16) & 0xff);  //stored in bytes[1]
(x >> (8) & 0xff);   //stored in bytes[2]
(x >> (0) & 0xff);   //stored in bytes[3]

and not the other way round

This is used to decode

  public int stringToInt(String bytesStr) {
    int result = 0;
    for(char b : bytesStr.toCharArray()) {
      result = (result << 8) + (int)b;
    }
    return result;
  }

I know that & 0xff is used to mask and collect 8 bits at a time. I just don't why is it in that order? Can anyone explain? Thank you.

3
  • Either way around works. This is "big endian" conversion because the first byte is taken from the "big" end of the integer. The other way is "little endian" conversion. It doesn't matter which you use, so long as the software doing the encoding and the software doing the decoding are in agreement. Commented Mar 25, 2020 at 2:26
  • 2
    Also, in Java, this is a terrible idea. Use a byte[], not char[] or use a ByteBuffer. Storing stuff in strings is done in other languages which do not have Java's strong support for IO, streams, and buffers. Commented Mar 25, 2020 at 2:28
  • 4
    Yikes, I didn't even notice that. I looked at the variable called bytes and my brain just said "those are bytes". Don't ever call your char array bytes or your byte array chars. Likewise for any other two data types. Commented Mar 25, 2020 at 2:32

1 Answer 1

1

You could use any order you want. The ordering of bytes in a computer number is called endianness https://en.wikipedia.org/wiki/Endianness

What you are seeing used here has the most significant byte first and is called "big endian". It's used in many network protocols and file formats. The reverse order is called "little endian" and it's the native byte order on most machines nowadays (x86 and most arm CPUs). Depending on what you do one order may be more convenient than the other.

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.