如何在 for 循环中编写附加代码块
How to write attached code block in a for loop
如何在简单的 for 循环中编写以下代码:
int asInt = (valueAsBytes[3] & 0xFF)
| ((valueAsBytes[2] & 0xFF) << 8)
| ((valueAsBytes[1] & 0xFF) << 16)
| ((valueAsBytes[0] & 0xFF) << 24);
注意数组索引在每次访问valueAsBytes
时减1,而移位运算符的第二个操作数增加8:
int asInt = 0;
for (int i = valueAsBytes.length-1; i >= 0; i--)
asInt |= valueAsBytes[i] & 0xFF << (valueAsBytes.length-i)*8;
我可以建议一个不同的解决方案吗?
我认为循环不会向此代码添加任何 "clarity"。真正的问题是您将 (valueAsBytes[i] & 0xFF) 之类的代码复制了四次。
如果有的话,你可以这样做:
int asInt = maskIndexedValueAndShiftBy(3, 0) | maskIndexedValueAndShiftBy(2, 8) | ...
和
private final int maskIndexedValueAndShiftBy(int index, int shifter) {
return (valueAsBytes[index] & 0xFF) << shifter;
循环只会让整个计算更难理解。
如何在简单的 for 循环中编写以下代码:
int asInt = (valueAsBytes[3] & 0xFF)
| ((valueAsBytes[2] & 0xFF) << 8)
| ((valueAsBytes[1] & 0xFF) << 16)
| ((valueAsBytes[0] & 0xFF) << 24);
注意数组索引在每次访问valueAsBytes
时减1,而移位运算符的第二个操作数增加8:
int asInt = 0;
for (int i = valueAsBytes.length-1; i >= 0; i--)
asInt |= valueAsBytes[i] & 0xFF << (valueAsBytes.length-i)*8;
我可以建议一个不同的解决方案吗?
我认为循环不会向此代码添加任何 "clarity"。真正的问题是您将 (valueAsBytes[i] & 0xFF) 之类的代码复制了四次。 如果有的话,你可以这样做:
int asInt = maskIndexedValueAndShiftBy(3, 0) | maskIndexedValueAndShiftBy(2, 8) | ...
和
private final int maskIndexedValueAndShiftBy(int index, int shifter) {
return (valueAsBytes[index] & 0xFF) << shifter;
循环只会让整个计算更难理解。