Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write attached code block in a for loop

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);
like image 539
Vishruth V Athrey Avatar asked Dec 12 '16 10:12

Vishruth V Athrey


2 Answers

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;
like image 133
Eran Avatar answered Oct 11 '22 01:10

Eran


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.

like image 32
GhostCat Avatar answered Oct 11 '22 00:10

GhostCat