我正在通过 Jay Bryant 的《Java 7 for Absolute Beginners》一书学习 Java。第 164 页上有一个特定的示例,他使用如下特定方法读取并反转了文本文件的内容:
private static void reverseByteArray(byte[] inBytes) {
int inLength = inBytes.length;
for (int i = 0; i < (inLength >>1); i++) {
byte temp = inBytes[i];
inBytes[i] = inBytes[inLength - i - 1];
inBytes[inLength - i - 1] = temp;
}
}
我的问题是按位移位运算符在以下行中做什么 for (int i = 0; i <(inLength >>1); i++) {
-它在整个文本内容反转操作中起什么作用?
我相信我理解了for循环下的后续代码,即将第一个字节的值与最后一个字节的值交换。
如果不存在按位移位运算符,则输出不会反转。
初始: sleep :也许会做梦:哎,有麻烦了; 因为在死亡的沉睡中,梦想可能会到来 当我们摆脱这尘世的束缚时, 必须让我们停下来:这是尊重 才造成如此长寿的灾难
输出: 埃菲尔·诺尔·奥斯·福伊蒂马拉克·塞卡姆·塔赫特 tcepser eht s'ereht :esuap su evig tsuM ,lioc latrom siht ffo dellffuhs evah ew nehW emoc yam smaerd tahw htaed fo 皮 taht ni roF ;bur eht s'ereht,ya:maerd ot ecnahcrep :剥离 oT
谢谢。
最佳答案
what does the bitwise shift operator do in the following line
要反转数组,您只需迭代直到其长度的一半。这就是位移运算符正在做的事情。位移 1 会截断最后一位,相当于除以 2。
length >> 1 == length / 2
If there is no bitwise shift operator present, the output will not be reversed
如果迭代到length
,那么直到length/2
,每个元素将与末尾的相应元素交换。但是,进一步进行将开始交换元素,元素朝左。因此,最终的数组将与原始数组相同。
考虑这个简单的例子:arr = [1, 2, 3, 4, 5]
从索引
0
开始,将arr[0]
与arr[4]
交换,数组变为:[5, 2, 3, 4, 1]
index = 1
,将arr[1]
与arr[3]
交换:[5, 4, 3, 2, 1]
到这里一切都很好,你只需在一半长度之前迭代即可。现在,如果您继续:
<index = 2
,交换arr[2]
和arr[2]
,没有变化index = 3
,交换arr[3]
和arr[1]
:[5, 2, 3, 4, 1]
看,数组开始更改为之前的状态。
关于Java - 在本例中如何使用按位移位运算符反转字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18159676/