How do I write following code in a simple for loop:
int asInt = (valueAsBytes[3] & 0xFF)
| ((valueAsBytes[2] & 0xFF) << 8)
| ((valueAsBytes[1] & 0xFF) << 16)
| ((valueAsBytes[0] & 0xFF) << 24);
Note that the array index decreases by 1 in each access to valueAsBytes
, while the second operand of the shift operator increases by 8 :
int asInt = 0;
for (int i = valueAsBytes.length-1; i >= 0; i--)
asInt |= valueAsBytes[i] & 0xFF << (valueAsBytes.length-i)*8;
May I suggest a different solution?
I think a loop doesn't add any "clarity" to this code. The real issue is that you are duplicating code like (valueAsBytes[i] & 0xFF) four times. If at all, you could do something like:
int asInt = maskIndexedValueAndShiftBy(3, 0) | maskIndexedValueAndShiftBy(2, 8) | ...
with
private final int maskIndexedValueAndShiftBy(int index, int shifter) {
return (valueAsBytes[index] & 0xFF) << shifter;
The loop just makes the whole computation harder to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With