<p>I am not sure how this is actually implemented in the code, but you can approximate the new target (nBits) value with data from the prior 2016th block. Note that as described <a href="https://bitcoin.stackexchange.com/a/36228/127579">above</a> nBits is the 32-bit compact encoding of the 256-bit target value.</p>
<p><a href="https://bitcoin.stackexchange.com/a/5840/127579">Here</a> shows the new difficulty (d_new) as:</p>
<p>d_new = d_old * 2 weeks / t_old</p>
<p>where 'old' signifies the previous 2016 blocks, and t_old is the time it took to find those previous 2016 blocks.</p>
<p><a href="https://bitcoin.stackexchange.com/a/66884/127579">Here</a> shows d_new from genesis block values as:</p>
<p>d_new = nBits_genesis / nBits_new, and similarly<br />
d_old = nBits_genesis / nBits_old</p>
<p>Combining these 3 equations results in</p>
<p>nBits_new = (t_old / 2 weeks) * nBits_old</p>
<p>So knowing the timestamps of the new block and the prior 2016th block, and the target of the prior 2016th block, we can approximate the new target value. For example:</p>
<p>block <a href="https://btc.com/btc/block/703584" rel="nofollow noreferrer">703584</a><br />
nBits = 0x170e2632 = 927282 * 256^(23-3)<br />
timestamp 2021-10-04 16:35:19</p>
<p>block <a href="https://btc.com/btc/block/701568" rel="nofollow noreferrer">701568</a> (the prior 2016th block)<br />
nBits = 0x170ed0eb = 970987 * 256^(23-3)<br />
timestamp 2021-09-21 07:34:36</p>
<p>So<br />
t_old = 13 days 9h 33s = 1155633s and 2 weeks = 1209600s<br />
nBits_old = 970987 * 256^(23-3)<br />
Thus the new target is approximately<br />
1155633/1209600 * 256^20<br />
= 0.955384424 * 970987 * 256^20 = 927666 * 256^20</p>
<p>Converting to the compact 32-bit format we get
nBits_new ~ 0x170e27b2</p>
<p>The mantissa 927666 (0x0e27b2) is close to the actual mantissa 927282 (0x0e2632).  It's a reasonable approximation but obviously the absolute values of the targets are quite different because it's base-256. Error here is likely due to rounding to the nearest second in the timestamps. Even though this is not the explicit calculation done in the code, I hope that it helps in general understanding, including the references <a href="https://bitcoin.stackexchange.com/a/5840/127579">here</a> and <a href="https://bitcoin.stackexchange.com/a/66884/127579">here</a>.</p>

CC BY-SA 4.0
2021-10-09T00:19:10.610Z
2021-10-09T00:19:10.610Z
hutchman
<p>I have a working c# implementation of nBits computation. I've tested and it works. However, keep in mind my machine is Little Endian so the implementation takes that into account. If your machine is Big Endian, then the way you would read in the nBits bytes would be different.
If you don't know how to get changeFactor, the steps are below after the code.</p>
<p>changeFactor is the ratio of time it took to mine the last <strong>2015</strong> blocks to the expected time of 10mins per block. {Pls it is not a typo. It is the last 2015 blocks you will consider when computing change factor even though you only recalculate nBits after every 2016 blocks}.</p>
<p>actual time of last 2015 blocks = unixEpoch of current highest block - unixEpoch of block with blockHeight equals [currentHighestBlockHeight - 2014] {again this is not a typo}</p>
<p>expected time = 2016 * 10 * 60 = 1209600</p>
<p>change factor = actualTime / expectedTime.
However, there is a limit for change factor. There can't be a change of more than 400% per retarget cycle.</p>
<p>so after getting change factor you do the ff. to keep it within the set bounds before feeding it to the retargeting function.</p>
<pre><code>if (changeFactor &gt; 4) changeFactor = 4;
if (changeFactor &lt; 0.25) changeFactor = 0.25;
</code></pre>
<p>Finally oldNBits is just the nBits of the current Highest block in uint form.
Hope this helps.</p>
<pre><code>public static uint RetargetByFactor(uint oldNBits, double changeFactor)
        {
            // convert change factor to rational number with numerator and denomenator
            BigInteger numerator = 0;
            BigInteger denomenator = 1;

            while(changeFactor % 1 != 0)
            {
                changeFactor = changeFactor * 10;
                denomenator = denomenator * 10;
            }
            numerator = (BigInteger)changeFactor;

            byte[] oldNBitsBytes = BitConverter.GetBytes(oldNBits);
            byte[] mantissa = new byte[] {oldNBitsBytes[0], oldNBitsBytes[1], oldNBitsBytes[2], 0x00 };  // need to reverse the bytes because we want the mantissa in little endian
            byte exponent = oldNBitsBytes[3];

            BigInteger result = new BigInteger(mantissa);
            result = result &lt;&lt; (exponent-3)*8;

            result = result * numerator / denomenator;

            byte[] resultBytes = result.ToByteArray();

            if (result == 0)
            {
                return 0;
            }

            // now to get the exponent of the newNBits, we count how many binary right shifts are needed for result to go below or equal to 0xffffff.
            byte newExponent = 3;
            while(result &gt; 0xffffff)
            {
                result = result &gt;&gt; 8;
                newExponent++;
            }

            BigInteger newMantissa = result;

            List&lt;byte&gt; compressedResult = new List&lt;byte&gt;();
            byte[] newMantissaBytes = newMantissa.ToByteArray();

            
            compressedResult.AddRange(new byte[] { newMantissaBytes[0], newMantissaBytes[1], newMantissaBytes[2] });

            compressedResult.Add(newExponent);

            return BitConverter.ToUInt32(compressedResult.ToArray(), 0);
        }
</code></pre>

CC BY-SA 4.0
2022-02-04T11:18:22.630Z
Finally, let me add that you only compute nBits for all blocks whose blockHeight % 2016 equals zero.
Mustapha Othman
CC BY-SA 4.0
2022-02-04T11:00:46.007Z
2022-02-04T11:14:08.147Z
2022-02-04T11:14:08.147Z
Mustapha Othman
<p>The target section of the block header is called <em>nBits</em> in the code.  nBits is a 32-bit compact encoding of a 256-bit target threshold.  It works like scientific notation, except that it uses base-256 instead of base-10.  For example, if nBits is equal to 0x181bc330, you would calculate it like this:</p>
<p><img src="https://developer.bitcoin.org/_images/en-nbits-overview.svg" alt="nBits formula" /></p>
<p>Or, more simply, you'd use the same shorthand you use with regular scientific notation:</p>
<p><img src="https://developer.bitcoin.org/_images/en-nbits-quick-parse.svg" alt="nBits quick" /></p>
<p>At a re-target point (every 2,016th block), Bitcoin Core adjusts nBits according to the rules described <a href="https://bitcoin.stackexchange.com/questions/5838/how-is-difficulty-calculated">in this answer</a> except that it is important to note that when difficulty changes by <em>p</em> percent, nBits is adjusted by the inverse (<em>-p</em> percent).  That's because a lower target is harder to reach the way Bitcoin is implemented.</p>
<p>It's also important to note that you can't just adjust the exponent part of nBits in the obvious way because when Satoshi first wrote the code, he inherited from a signed type---so extra care must be taken not to create a negative nBits value.  The Bitcoin.org Developer Reference has <a href="https://bitcoin.org/en/developer-reference#target-nbits" rel="nofollow noreferrer">more details</a> (but be careful, I haven't yet had an expert review that section).</p>

CC BY-SA 4.0
2019-09-26T12:35:33.403Z
Can you elaborate on how this is Base-256? Surely for base 256 we would need 256 unique symbols?
El Ronnoco
CC BY-SA 4.0
2021-02-10T14:57:17.613Z
@ElRonnoco It does have 256 unique symbols: each byte is a symbol. (For the analogy, anyway; exponential notation doesn't actually require the base to line up with symbols at all; in fact, mathematicians use base $e$ a _lot_.)
wizzwizz4
CC BY-SA 4.0
2015-02-26T13:43:33.337Z
2023-05-23T16:07:23.027Z
2023-05-23T16:07:23.027Z
David A. Harding
<p>I've been poking around <a href="https://en.bitcoin.it/wiki/Target" rel="noreferrer">https://en.bitcoin.it/wiki/Target</a> and I've found the current target, but I can't seem to find how it's generated. It's supposedly generated when the difficulty is adjusted, as stated here: <a href="https://en.bitcoin.it/wiki/Block_hashing_algorithm" rel="noreferrer">https://en.bitcoin.it/wiki/Block_hashing_algorithm</a>, but what exactly is the algorithm for generating the target? If someone could show me some psuedocode that would be great.</p>

CC BY-SA 3.0
2014-03-24T12:21:39.453Z
It is not clear to me whether you are looking for a verbal explanation of the difficulty algorithm, the specific line of code where to find it, or a step-by-step explanation of the code. Perhaps you could edit your question in order to clarify. If you are asking for the first: possible duplicate of [How is difficulty calculated?](http://bitcoin.stackexchange.com/q/5838/5406)
Murch
CC BY-SA 3.0
2014-03-24T15:54:06.590Z
Is difficulty the same thing as the target?
Dylan Katz
CC BY-SA 3.0
2014-03-24T22:23:45.537Z
Difficulty is essentially the human readable representation of the target. See here: [What is “difficulty” and how it relates to “target”?](http://bitcoin.stackexchange.com/q/8806/5406)
Murch
<protocol><algorithms><difficulty>
How is the target section of a block header calculated?
Dylan Katz
# How is the target section of a block header calculated?

(Asked by: username_0 on 2014-03-24)

I've been poking around <https://en.bitcoin.it/wiki/Target> and I've found the current target, but I can't seem to find how it's generated. It's supposedly generated when the difficulty is adjusted, as stated here: <https://en.bitcoin.it/wiki/Block_hashing_algorithm>, but what exactly is the algorithm for generating the target? If someone could show me some psuedocode that would be great.

**Tags:** protocol, algorithms, difficulty

> **Comments:**
> **username_1**: It is not clear to me whether you are looking for a verbal explanation of the difficulty algorithm, the specific line of code where to find it, or a step-by-step explanation of the code. Perhaps you could edit your question in order to clarify. If you are asking for the first: possible duplicate of [How is difficulty calculated?](http://bitcoin.stackexchange.com/q/5838/5406)  
> **username_0**: Is difficulty the same thing as the target?  
> **username_1**: Difficulty is essentially the human readable representation of the target. See here: [What is “difficulty” and how it relates to “target”?](http://bitcoin.stackexchange.com/q/8806/5406)  

---

## 3 answers

### Answer by username_4 on 2015-02-26. Score: 19 | Accepted answer

The target section of the block header is called *nBits* in the code. nBits is a 32-bit compact encoding of a 256-bit target threshold. It works like scientific notation, except that it uses base-256 instead of base-10. For example, if nBits is equal to 0x181bc330, you would calculate it like this:

![nBits formula](https://developer.bitcoin.org/_images/en-nbits-overview.svg)

Or, more simply, you'd use the same shorthand you use with regular scientific notation:

![nBits quick](https://developer.bitcoin.org/_images/en-nbits-quick-parse.svg)

At a re-target point (every 2,016th block), Bitcoin Core adjusts nBits according to the rules described [in this answer](https://bitcoin.stackexchange.com/questions/5838/how-is-difficulty-calculated) except that it is important to note that when difficulty changes by *p* percent, nBits is adjusted by the inverse (*-p* percent). That's because a lower target is harder to reach the way Bitcoin is implemented.

It's also important to note that you can't just adjust the exponent part of nBits in the obvious way because when Satoshi first wrote the code, he inherited from a signed type---so extra care must be taken not to create a negative nBits value. The Bitcoin.org Developer Reference has [more details](https://bitcoin.org/en/developer-reference#target-nbits) (but be careful, I haven't yet had an expert review that section).

> **Comments:**
> **username_5**: Can you elaborate on how this is Base-256? Surely for base 256 we would need 256 unique symbols?  
> **username_6**: @username_5 It does have 256 unique symbols: each byte is a symbol. (For the analogy, anyway; exponential notation doesn't actually require the base to line up with symbols at all; in fact, mathematicians use base $e$ a _lot_.)  

---

### Answer by username_2 on 2021-10-09. Score: 1

I am not sure how this is actually implemented in the code, but you can approximate the new target (nBits) value with data from the prior 2016th block. Note that as described [above](https://bitcoin.stackexchange.com/a/36228/127579) nBits is the 32-bit compact encoding of the 256-bit target value.

[Here](https://bitcoin.stackexchange.com/a/5840/127579) shows the new difficulty (d\_new) as:

d\_new = d\_old \* 2 weeks / t\_old

where 'old' signifies the previous 2016 blocks, and t\_old is the time it took to find those previous 2016 blocks.

[Here](https://bitcoin.stackexchange.com/a/66884/127579) shows d\_new from genesis block values as:

d\_new = nBits\_genesis / nBits\_new, and similarly  
d\_old = nBits\_genesis / nBits\_old

Combining these 3 equations results in

nBits\_new = (t\_old / 2 weeks) \* nBits\_old

So knowing the timestamps of the new block and the prior 2016th block, and the target of the prior 2016th block, we can approximate the new target value. For example:

block [703584](https://btc.com/btc/block/703584)  
nBits = 0x170e2632 = 927282 \* 256^(23-3)  
timestamp 2021-10-04 16:35:19

block [701568](https://btc.com/btc/block/701568) (the prior 2016th block)  
nBits = 0x170ed0eb = 970987 \* 256^(23-3)  
timestamp 2021-09-21 07:34:36

So  
t\_old = 13 days 9h 33s = 1155633s and 2 weeks = 1209600s  
nBits\_old = 970987 \* 256^(23-3)  
Thus the new target is approximately  
1155633/1209600 \* 256^20  
= 0.955384424 \* 970987 \* 256^20 = 927666 \* 256^20

Converting to the compact 32-bit format we get
nBits\_new ~ 0x170e27b2

The mantissa 927666 (0x0e27b2) is close to the actual mantissa 927282 (0x0e2632). It's a reasonable approximation but obviously the absolute values of the targets are quite different because it's base-256. Error here is likely due to rounding to the nearest second in the timestamps. Even though this is not the explicit calculation done in the code, I hope that it helps in general understanding, including the references [here](https://bitcoin.stackexchange.com/a/5840/127579) and [here](https://bitcoin.stackexchange.com/a/66884/127579).


---

### Answer by username_3 on 2022-02-04. Score: 0

I have a working c# implementation of nBits computation. I've tested and it works. However, keep in mind my machine is Little Endian so the implementation takes that into account. If your machine is Big Endian, then the way you would read in the nBits bytes would be different.
If you don't know how to get changeFactor, the steps are below after the code.

changeFactor is the ratio of time it took to mine the last **2015** blocks to the expected time of 10mins per block. {Pls it is not a typo. It is the last 2015 blocks you will consider when computing change factor even though you only recalculate nBits after every 2016 blocks}.

actual time of last 2015 blocks = unixEpoch of current highest block - unixEpoch of block with blockHeight equals [currentHighestBlockHeight - 2014] {again this is not a typo}

expected time = 2016 \* 10 \* 60 = 1209600

change factor = actualTime / expectedTime.
However, there is a limit for change factor. There can't be a change of more than 400% per retarget cycle.

so after getting change factor you do the ff. to keep it within the set bounds before feeding it to the retargeting function.

```
if (changeFactor > 4) changeFactor = 4;
if (changeFactor < 0.25) changeFactor = 0.25;

```

Finally oldNBits is just the nBits of the current Highest block in uint form.
Hope this helps.

```
public static uint RetargetByFactor(uint oldNBits, double changeFactor)
        {
            // convert change factor to rational number with numerator and denomenator
            BigInteger numerator = 0;
            BigInteger denomenator = 1;

            while(changeFactor % 1 != 0)
            {
                changeFactor = changeFactor * 10;
                denomenator = denomenator * 10;
            }
            numerator = (BigInteger)changeFactor;

            byte[] oldNBitsBytes = BitConverter.GetBytes(oldNBits);
            byte[] mantissa = new byte[] {oldNBitsBytes[0], oldNBitsBytes[1], oldNBitsBytes[2], 0x00 };  // need to reverse the bytes because we want the mantissa in little endian
            byte exponent = oldNBitsBytes[3];

            BigInteger result = new BigInteger(mantissa);
            result = result << (exponent-3)*8;

            result = result * numerator / denomenator;

            byte[] resultBytes = result.ToByteArray();

            if (result == 0)
            {
                return 0;
            }

            // now to get the exponent of the newNBits, we count how many binary right shifts are needed for result to go below or equal to 0xffffff.
            byte newExponent = 3;
            while(result > 0xffffff)
            {
                result = result >> 8;
                newExponent++;
            }

            BigInteger newMantissa = result;

            List<byte> compressedResult = new List<byte>();
            byte[] newMantissaBytes = newMantissa.ToByteArray();

            
            compressedResult.AddRange(new byte[] { newMantissaBytes[0], newMantissaBytes[1], newMantissaBytes[2] });

            compressedResult.Add(newExponent);

            return BitConverter.ToUInt32(compressedResult.ToArray(), 0);
        }

```

> **Comments:**
> **username_3**: Finally, let me add that you only compute nBits for all blocks whose blockHeight % 2016 equals zero.  

---

