nBits
refers to the target. The target is inversely proportional to the difficulty, and is encoded as a compact representation of a 256-bit number. The first byte of the 32-bit field represents an exponent and the remaining 3 bytes encode a mantissa.
Image via btcinformation.org
E.g. the first (and maximum) target was 0x1d00ffff
, which is the compact representation of 0x00000000ffff0000000000000000000000000000000000000000000000000000
, a 256-bit number with the leading 32 bits set to zero, followed by sixteen bits set to one, followed by the remaining bits not defined by the mantissa also being set to zero.
The block hash is usually represented as a hexadecimal number (which include the letters from A–F
for the numbers 10-15), but block hashes result from SHA256d hashing and the output of SHA256 is a 256-bit number (hence the name). When miners are searching for a valid block, they create a multitude of block candidates. When one of these candidates' hash digests (interpreted as a 256-bit number) is smaller than or equal than the target, the miner has found a valid block.
You can calculate the difficulty from the target with the following formula:
difficulty = max_target / current_target
where max_target
stands for the above mention initial target and corresponds to the minimum difficulty. Alternatively, the formula works out to:
difficulty = 2^208 * 65535 / current_target.