# 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

• Does this answer your question? What does the nBits value represent? Feb 10 at 14:54
• @MCCCS I did look at that before, but I don't see where it says the formula for calculating the nBits of a Block? I was under the impression Difficulty and nBits were different.
– L M
Feb 10 at 15:17
• @LM No, they're arguably the same. The difficulty is just a human-friendly way of representing the same information. Target, nBits, and difficulty are all conceptually the same. Feb 10 at 19:23

`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.

• So how did the Genesis Block gets its nBit value if it relies on the previous block? Is it similar to the previous hash in the Genesis Block where it was just given a random value?
– L M
Feb 10 at 19:00
• The genesis block is valid by definition; its contents does not matter. Feb 10 at 19:22