This question already has answers here:
Converting hexadecimal to float in JavaScript
(9 answers)
Closed 5 years ago.
I am trying to convert a hex string to a float number in Javascript.
Suppose that I have the hex string "0082d241". Using this online converter and selecting Swap endianness, the correct float value is 26,3135.
I know that this is the correct answer because it is from a TMP36 sensor.
I have tried some other examples that I found here on SO, such as Converting hexadecimal to float in javascript, but none of them worked.
The first step is to swap endianness, using the source code found on the page that you've shown.
Then you can convert the hexadecimal string to a float value.
function flipHexString(hexValue, hexDigits) {
var h = hexValue.substr(0, 2);
for (var i = 0; i < hexDigits; ++i) {
h += hexValue.substr(2 + (hexDigits - 1 - i) * 2, 2);
}
return h;
}
function hexToFloat(hex) {
var s = hex >> 31 ? -1 : 1;
var e = (hex >> 23) & 0xFF;
return s * (hex & 0x7fffff | 0x800000) * 1.0 / Math.pow(2, 23) * Math.pow(2, (e - 127))
}
console.log(hexToFloat(flipHexString("0x0082d241", 8)));
console.log(hexToFloat(flipHexString("0x5d7e2842", 8)));
Related
This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 10 months ago.
I Want to convert Hexadecimal to Float 32. I have used below mention code but it didn't help me proper as I try to convert 0x4145851f this value to float32 it comes as a 12.345000267028809 But actually the value is 12.345 so I want to ignore extra digits. not rounding off, need proper output.
const HexToFloat32 = (str) => {
var int = parseInt(str, 16);
if (int > 0 || int < 0) {
var sign = int >>> 31 ? -1 : 1;
var exp = ((int >>> 23) & 0xff) - 127;
var mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
var float32 = 0;
for (let i = 0; i < mantissa.length; i += 1) {
float32 += parseInt(mantissa[i]) ? Math.pow(2, exp) : 0;
exp--;
}
return float32 * sign;
} else return 0;
};
console.log(HexToFloat32("0x41200000"));
I already go through with below mention Stack URL:
stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript
I need to convert this hex "46b76833" to float, and I need to get this value 23476.1
I written a code to get hex and everything else but this step I don't know how to do, can someone help me? Thanks in advance!
I tried something like this but it doesn't work.
function hexToFloat(hex) {
var s = hex >> 31 ? -1 : 1;
var e = (hex >> 23) & 0xFF;
var rez = s * (hex & 0x7fffff | 0x800000) * 1.0 / Math.pow(2, 23) * Math.pow(2, (e - 127));
return rez
}
You're nearly there, we just need to convert the hex string to a number before we tranform to a float.
The MSB is the sign, the following 8 bits are the exponent, then the last 23 bits represent the fraction of the number.
This is an IEEE Single Precision floating point number, there are more details here
function hexStringToFloat(hexString) {
const hex = parseInt(hexString, 16);
const sign = hex >> 31 ? -1 : 1;
const exponent = (hex >> 23) & 0xFF;
return sign * (hex & 0x7fffff | 0x800000) * 1.0 / Math.pow(2, 23) * Math.pow(2, (exponent - 127));
}
console.log("Result:", hexStringToFloat("46b76833"));
This question already has answers here:
How to format numbers? [duplicate]
(17 answers)
Closed 3 years ago.
I'm trying to create a function that will format a number received from the user's input so that it will add commas in the right places. For example, a 1000 becomes a 1,000. A 1000000 becomes a 1,000,000 an so on.
var formatNumber = function (num) {
var numSplit, dec, int;
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
dec = numSplit[1];
if (int.length > 3 && int.length <= 6) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 4);
} else if (int.length > 6) {
int = int.substr(0, int.length - 6) + ',' + int.substr(int.length - 6, int.length - 4) + ',' + int.substr(int.length - 3, 7);
}
return int + '.' + dec
}
The function works great for numbers with up to 7 digits. 1 million turns into 1,000,000.00 perfectly, but above that it adds another zero, so a 10 million becomes 10,0000,000.00 . How can this be fixed?
Here's a codepen: https://codepen.io/samivino/pen/ZEzRjjy
P.s.- Numbers higher than 999,999,999 are not relevant, so there's no need to add more that 2 commas.
You can simply use toLocaleString()
var number = 1000000;
var formatted = number.toLocaleString();
console.log(formatted) //1,000,000
Read here for more information on how to use it.
I have an existing fn that does the following:
public GetColor = (argb: number) => {
var a = 1;// (argb & -16777216) >> 0x18; // gives me FF
var r = (argb & 0xff0000) >> 0x10;
var g = (argb & 0x00ff00) >> 0x8;
var b = (argb & 0x0000ff);
var curKendoColor = kendo.parseColor("rgba(" + r + "," + g + "," + b + "," + a + ")", false);
I would like to know the function I would need to return that back to a number.
for example if i have AARRGGBB of (FFFF0000) and I would like to get back to the number version that toColor would have derived from.
I would be ok with the unsigned version of the return number or the signed version. Unsigned would be -65536 but the unsigned would be fine as well (not sure what that number would be off top of my head now)
I tried to do this but the attempts all end out at 0 which i know is not correct:
colorSend |= (parseInt(this.Color.substr(0,2),16) & 255) << 24;
colorSend |= (parseInt(this.Color.substr(1, 2), 16) & 255) << 16;
colorSend |= (parseInt(this.Color.substr(3, 2), 16) & 255) << 8;
the parseInt gives me the 255,0,0 that I think I would expect but the & and the shift logic does not seem correct because & zeros the integers out thus the result was 0
Ok I was able to get something that seems to work for me. I am simplifying it a bit but for the ARGB i can do something like
val = "0xFFFF0000"
val = parseInt(val, 16)
if((val & 0x80000000) != 0)
{
val = val - 0x100000000;
}
So for example for Red with an A of FF I would get-
-65536 or with unsigned I can omit the last part.
Actually it's pretty easy. You just have to understand what the HEX values mean.
In the hexadecimal system each number from 10 to 15 is represented by the letters A to F. The numbers lower ten are normal numbers 1 - 9. So if you want to convert 11 into hex it would be 0B. Because you need no number below 11 (0) and the letter B represents 11. If you read a little bit about the hex system, you should be able to write you new function very easily ;)
I would like to convert a number in base 10 with fraction to a number in base 16.
var myno = 28.5;
var convno = myno.toString(16);
alert(convno);
All is well there. Now I want to convert it back to decimal.
But now I cannot write:
var orgno = parseInt(convno, 16);
alert(orgno);
As it doesn't return the decimal part.
And I cannot use parseFloat, since per MDC, the syntax of parseFloat is
parseFloat(str);
It wouldn't have been a problem if I had to convert back to int, since parseInt's syntax is
parseInt(str [, radix]);
So what is an alternative for this?
Disclaimer: I thought it was a trivial question, but googling didn't give me any answers.
This question made me ask the above question.
Another possibility is to parse the digits separately, splitting the string up in two and treating both parts as ints during the conversion and then add them back together.
function parseFloat(str, radix)
{
var parts = str.split(".");
if ( parts.length > 1 )
{
return parseInt(parts[0], radix) + parseInt(parts[1], radix) / Math.pow(radix, parts[1].length);
}
return parseInt(parts[0], radix);
}
var myno = 28.4382;
var convno = myno.toString(16);
var f = parseFloat(convno, 16);
console.log(myno + " -> " + convno + " -> " + f);
Try this.
The string may be raw data (simple text) with four characters (0 - 255) or
a hex string "0xFFFFFFFF" four bytes in length.
jsfiddle.net
var str = '0x3F160008';
function parseFloat(str) {
var float = 0, sign, order, mantissa, 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 parameter');
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;
}
Please try this:
function hex2dec(hex) {
hex = hex.split(/\./);
var len = hex[1].length;
hex[1] = parseInt(hex[1], 16);
hex[1] *= Math.pow(16, -len);
return parseInt(hex[0], 16) + hex[1];
}
function hex2dec(hex) {
hex = hex.split(/\./);
var len = hex[1].length;
hex[1] = parseInt(hex[1], 16);
hex[1] *= Math.pow(16, -len);
return parseInt(hex[0], 16) + hex[1];
}
// ----------
// TEST
// ----------
function calc(hex) {
let dec = hex2dec(hex);
msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(16)}</b>`
}
let init="bad.a55";
inp.value=init;
calc(init);
<input oninput="calc(this.value)" id="inp" /><div id="msg"></div>
I combined Mark's and Kent's answers to make an overloaded parseFloat function that takes an argument for the radix (much simpler and more versatile):
function parseFloat(string, radix)
{
// Split the string at the decimal point
string = string.split(/\./);
// If there is nothing before the decimal point, make it 0
if (string[0] == '') {
string[0] = "0";
}
// If there was a decimal point & something after it
if (string.length > 1 && string[1] != '') {
var fractionLength = string[1].length;
string[1] = parseInt(string[1], radix);
string[1] *= Math.pow(radix, -fractionLength);
return parseInt(string[0], radix) + string[1];
}
// If there wasn't a decimal point or there was but nothing was after it
return parseInt(string[0], radix);
}
Try this:
Decide how many digits of precision you need after the decimal point.
Multiply your original number by that power of 16 (e.g. 256 if you want two digits).
Convert it as an integer.
Put the decimal point in manually according to what you decided in step 1.
Reverse the steps to convert back.
Take out the decimal point, remembering where it was.
Convert the hex to decimal in integer form.
Divide the result by the the appropriate power of 16 (16^n, where n is the number of digits after the decimal point you took out in step 1).
A simple example:
Convert decimal 23.5 into hex, and want one digit after the decimal point after conversion.
23.5 x 16 = 376.
Converted to hex = 0x178.
Answer in base 16: 17.8
Now convert back to decimal:
Take out the decimal point: 0x178
Convert to decimal: 376
Divide by 16: 23.5
I'm not sure what hexadecimal format you wanted to parse there. Was this something like: "a1.2c"?
Floats are commonly stored in hexadecimal format using the IEEE 754 standard. That standard doesn't use any dots (which don't exist in pure hexadecimal alphabet). Instead of that there are three groups of bits of predefined length (1 + 8 + 23 = 32 bits in total ─ double uses 64 bits).
I've written the following function for parsing such a numbers into float:
function hex2float(num) {
var sign = (num & 0x80000000) ? -1 : 1;
var exponent = ((num >> 23) & 0xff) - 127;
var mantissa = 1 + ((num & 0x7fffff) / 0x7fffff);
return sign * mantissa * Math.pow(2, exponent);
}
Here is a size-improvement of Mark Eirich's answer:
function hex2dec(hex) {
let h = hex.split(/\./);
return ('0x'+h[1])*(16**-h[1].length)+ +('0x'+h[0]);
}
function hex2dec(hex) {
let h = hex.split(/\./);
return ('0x'+h[1])*(16**-h[1].length)+ +('0x'+h[0]);
}
function calc(hex) {
let dec = hex2dec(hex);
msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(16)}</b>`
}
let init = "bad.a55";
inp.value = init;
calc(init);
<input oninput="calc(this.value)" id="inp" /><div id="msg"></div>
private hexStringToFloat(hexString: string): number {
return Buffer.from(hexString, 'hex').readFloatBE(0);
}
Someone might find this useful.
bytes to Float32
function Int2Float32(bytes) {
var sign = (bytes & 0x80000000) ? -1 : 1;
var exponent = ((bytes >> 23) & 0xFF) - 127;
var significand = (bytes & ~(-1 << 23));
if (exponent == 128)
return sign * ((significand) ? Number.NaN : Number.POSITIVE_INFINITY);
if (exponent == -127) {
if (significand === 0) return sign * 0.0;
exponent = -126;
significand /= (1 << 22);
} else significand = (significand | (1 << 23)) / (1 << 23);
return sign * significand * Math.pow(2, exponent);
}