Java - how does reversing byte array with bitwise shift operator work in this example? -
i learning java book - java 7 absolute beginners jay bryant. there particular example on page 164 read , reversed contents of text file, using particular method follows:
private static void reversebytearray(byte[] inbytes) { int inlength = inbytes.length; (int = 0; < (inlength >>1); i++) { byte temp = inbytes[i]; inbytes[i] = inbytes[inlength - - 1]; inbytes[inlength - - 1] = temp; } }
my question bitwise shift operator in following line (int = 0; < (inlength >>1); i++) {
-what role in entire operation reverse text contents?
i believe understand subsequent code under loop, swap first byte's value last byte's value.
if there no bitwise shift operator present, output not reversed.
initial: sleep: perchance dream: ay, there's rub; in sleep of death dreams may come when have shuffled off mortal coil, must give pause: there's respect makes calamity of long life
output: efil gnol os fo ytimalac sekam taht tcepser eht s'ereht :esuap su evig tsum ,lioc latrom siht ffo delffuhs evah ew nehw emoc yam smaerd tahw htaed fo peels taht ni rof ;bur eht s'ereht ,ya :maerd ot ecnahcrep :peels ot
thank you.
what bitwise shift operator in following line
for reversing array, need iterate till it's half length. bit shift operator doing. bit shift 1 truncates last bit , equivalent divide 2.
length >> 1 == length / 2
if there no bitwise shift operator present, output not reversed
if iterate till length
, till length / 2
, each element swapped corresponding element end. but, proceeding further start swapping element, element towards left. so, final array same original.
consider simple example: arr = [1, 2, 3, 4, 5]
you start @ index
0
, , swaparr[0]
arr[4]
, array becomes:[5, 2, 3, 4, 1]
index = 1
, swaparr[1]
arr[3]
:[5, 4, 3, 2, 1]
till here fine, , iterate before half length. if proceed further:
index = 2
, swaparr[2]
,arr[2]
, no changeindex = 3
, swaparr[3]
,arr[1]
:[5, 2, 3, 4, 1]
see, array starts changing previous state.
Comments
Post a Comment