How are the nBits of a block calculated? 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?
Thanks
nBits is a compressed representation of the target value that the block's hash must be less than. Bitcoin does not actually care about difficulty. Difficulty is just for humans to think about how much work is actually being done. Bitcoin only cares about nBits and the target value it represents. A block's hash must be less than that target value. nBits is recalculated every time the difficulty changes. The calculation takes the previous target (previous nBits) and scales it by the ratio of the actual timespan it took for that difficulty period to the timespan that is targeted for a difficulty period.
What it code does is (in pseudocode):
new_target = last_block.nBits.uncompress();
new_target *= actual_timespan;
new_target /= target_timespan;
this_block.nBits = new_target.compress();

So nBits starts at the value of the genesis block, and then scales up and down depending on how quickly blocks are being mined.

The relationship between nBits and difficulty is inverted. As nBits represents a smaller and smaller target, the difficulty value goes up. The computation is essentially just the ratio between the current target value and the maximum target value, which also happens to be the target value found in the genesis block. The difficulty is the current target divided by the the maximum target.