So I've been trying to figure out how the nBits of a block is calculated, but I can't seem to come up with an answer. I know (think) that it's based off the difficulty of the block, but I'm still not sure exactly how it works. The Genesis Block for example has a difficulty of 1.0, yet the nBits for that block was 486,604,799 (0x1d00ffff). Then if we look at the most recent block, it has a difficulty level of 21,434,395,961,348.92, yet an nBits of 386,736,569 (0x170d21b9).
So my question is, how exactly is the nBits of a block calculated and what is its relation to the difficulty of a block?