Skip to content

Instantly share code, notes, and snippets.

@laerciobernardo
Last active January 21, 2024 14:48
Show Gist options
  • Save laerciobernardo/498f7ba1c269208799498ea8805d8c30 to your computer and use it in GitHub Desktop.
Save laerciobernardo/498f7ba1c269208799498ea8805d8c30 to your computer and use it in GitHub Desktop.
Convert Hexadecimal IEEE754 to Float in Javascript
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;
}
@gitsaycat
Copy link

gitsaycat commented Dec 20, 2018

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