Skip to content

Instantly share code, notes, and snippets.

@bigjosh
Last active June 1, 2021 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigjosh/c14c5d99a641b92a6bce7261a29c0b66 to your computer and use it in GitHub Desktop.
Save bigjosh/c14c5d99a641b92a6bce7261a29c0b66 to your computer and use it in GitHub Desktop.
Convert bitcoin `nBits` field into a hex string value for `target` using only string functions
// Returns a 64 char (256 bit) hex string of the target
// Based on https://developer.bitcoin.org/reference/block_chain.html#target-nbits
function nbits2target( nbits ) {
const significand = nbits & 0x00ffffff;
const exponent = nbits >>> (8*3);
// (all `*2` are becuase calcuations are in bytes, but in string 1 byte = 2 letter places)
const fixed6SigString = (significand.toString(16)).padStart( 3*2 , "0");
// a 3 digit (6 byte) hex string with a leading fixed point
const paddedSigString = ("00").repeat(32) + fixed6SigString + ("00").repeat(32) ;
// padded string has a fixed (hexa)decimal point after byte 32
const expString = paddedSigString.slice( exponent*2, (32+exponent)*2);
// Now we move the point to the right exp bytes
return expString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment