Last active
December 11, 2024 07:30
-
-
Save laerciobernardo/498f7ba1c269208799498ea8805d8c30 to your computer and use it in GitHub Desktop.
Convert Hexadecimal IEEE754 to Float in Javascript
This file contains hidden or 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
var str = '0x41FC6733'; | |
function parseFloat(str) { | |
var float = 0, sign, order, mantiss,exp, | |
int = 0, multi = 1; | |
if (/^0x/.exec(str)) { | |
int = parseInt(str,16); | |
}else{ | |
for (var i = str.length -1; i >=0; i -= 1) { | |
if (str.charCodeAt(i)>255) { | |
console.log('Wrong string parametr'); | |
return false; | |
} | |
int += str.charCodeAt(i) * multi; | |
multi *= 256; | |
} | |
} | |
sign = (int>>>31)?-1:1; | |
exp = (int >>> 23 & 0xff) - 127; | |
mantissa = ((int & 0x7fffff) + 0x800000).toString(2); | |
for (i=0; i<mantissa.length; i+=1){ | |
float += parseInt(mantissa[i])? Math.pow(2,exp):0; | |
exp--; | |
} | |
return float*sign; | |
} |
This was a very useful contribution, helped me convert a 4-byte decimal IEEE 754 encoded float32 value to its decimal value - thanks for sharing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing the code for the conversion.
I've made a gist file which uses your solution for the conversion but a little modified.
Link to the gist if you're interested https://gist.github.com/Jozo132/2c0fae763f5dc6635a6714bb741d152f