How to write an attached block of code in a for loop

How to write the following code in a simple loop:

int asInt = (valueAsBytes[3] & 0xFF) | ((valueAsBytes[2] & 0xFF) << 8) | ((valueAsBytes[1] & 0xFF) << 16) | ((valueAsBytes[0] & 0xFF) << 24); 
+5
source share
2 answers

Note that the index of the array decreases by 1 in each access to valueAsBytes , and 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; 
+5
source

Is there any other solution?

I think the loop does not add β€œclarity” to this code. The real problem is that you duplicate code like (valueAsBytes [i] and 0xFF) four times. If at all, you can 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 cycle simply complicates the understanding of all the calculations.

+2
source

Source: https://habr.com/ru/post/1261125/


All Articles