[英]How to write attached code block in a for loop
How do I write following code in a simple for loop: 如何在简单的for循环中编写以下代码:
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 : 请注意,每次访问valueAsBytes
时数组索引减1,而shift运算符的第二个操作数增加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. 真正的问题是你复制代码(valueAsBytes [i]&0xFF)四次。 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. 循环只会使整个计算更难理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.