I was going through the guide on this thread, and I was stuck on the problem 'Secret Cow Code' here: USA Computing Olympiad

I was able to write the code using the solution on the USACO website, but I don't understand how this snippet specifically works:

while(2*length <= index) {

length *= 2;

}

if(length == index) {

return parse(s, length-1);

}

return parse(s, index - length - 1);

Thanks!