Last active
June 1, 2021 01:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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