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.
byte[], notchar[]or use aByteBuffer. Storing stuff in strings is done in other languages which do not have Java's strong support for IO, streams, and buffers.bytesand my brain just said "those are bytes". Don't ever call yourchararraybytesor yourbytearraychars. Likewise for any other two data types.