Bitcoin Target, Bits, and Difficulty Explained — Part II
In the first 2 lines we are getting the block timestamps for block 213696 and block 215711, and getting the difference to calculate the ratio for these 2016 blocks.
We then check if the generated ratio is a factor of 4 to avoid creating a target value that is massively different from the previous target.
Then the new target is created by multiplying the ratio by the current network target and make sure that the new target is not greater than the original target (max target). The original target is what Satoshi was defined in the Genesis block as its target value.
The next step is to convert this target to a different form to be included in the block header, I mimicked that conversion by using a fake helper function in line 29. This function is supposed to return the official target value for the new target that is generated.