javascript 从/到位浮动 [英] javascript float from/to bits

查看:15
本文介绍了javascript 从/到位浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用任何其他语言而不是 javascript 执行一些脑残简单的事情:从浮点数中取出位(反之亦然).

在 C/C++ 中,它类似于

<前>浮动 a = 3.1415;int b = *((int*)&a);

反之亦然

<前>int a = 1000;浮动 b = *((浮动*)&a);

在 C# 中你可以使用 BitConverter...floatBits 或 Java 中的类似内容...即使在 VB6 中,看在上帝的份上,您也可以将 float32 内存转换为 int32.我到底如何在 javascript 中的 int 和 float 之间进行转换?

解决方案

您当然不会在 JavaScript 中获得任何低级的东西.允许以一种必须对不受信任的潜在攻击者网站安全使用的语言进行重铸和指针浮动是极其危险的.

如果你想在一个 Number 中获得一个单精度值的 32 位 IEEE754 表示(记住它也不是一个 int;你在 JavaScript 中获得的唯一数字类型是 double),您必须通过将符号、指数和尾数位放在一起来自己制作.有示例代码这里.

I am trying to perform something that is brain-dead simple in any other language but not javascript: get the bits out of float (and the other way around).

In C/C++ it would be something like

float a = 3.1415;
int b = *((int*)&a);

and vise-versa

int a = 1000;
float b = *((float*)&a);

In C# you can use the BitConverter ...floatBits or something alike in Java... Even in VB6 for Christ's sake you can memcpy a float32 into an int32. How on earth can I translate between and int and a float in javascript?

解决方案

You certainly don't get anything low-level like that in JavaScript. It would be extremely dangerous to allow recasting and pointer-frobbing in a language that has to be safe for untrusted potential-attacker web sites to use.

If you want to get a 32-bit IEEE754 representation of a single-precision value in a Number (which remember is not an int either; the only number type you get in JavaScript is double), you will have to make it yourself by fiddling the sign, exponent and mantissa bits together. There's example code here.

这篇关于javascript 从/到位浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆