[英]How to convert a float to an array of bytes?
I need to convert a float value (say 3.5) into an array of bytes in JavaScript. 我需要将浮点值(例如3.5)转换为JavaScript中的字节数组。
Research on this matter only seems to go in the other direction. 关于这个问题的研究似乎只朝另一个方向发展。
The application I'm writing lets the user input a float value, that is sent to a micro controller via Bluetooth. 我正在编写的应用程序允许用户输入一个浮点值,该值通过蓝牙发送到微控制器。
The particular data-protocol expects the value sequentially as bytes in little-endian order. 特定的数据协议期望该值按字节顺序以低端顺序排列。 Can someone help me?
有人能帮我吗?
(Sorry if my English is a bit off. It's not my first language.) (对不起,如果我的英语不太熟练。这不是我的母语。)
The simplest way is to use ArrayBuffer
: 最简单的方法是使用
ArrayBuffer
:
buf = new ArrayBuffer(64);
flt = new Float64Array(buf);
flt[0] = 12.34;
Now buf
contains the packed binary representation of the float number. 现在,
buf
包含浮点数的压缩二进制表示形式。 You can send it as is, if your API supports buffers, or convert it to an array of bytes: 如果您的API支持缓冲区,则可以按原样发送,也可以将其转换为字节数组:
bytes = new Uint8Array(buf);
for(var i = 0; i < 65; i++) {
console.log(bytes[i])
}
Probably note the shortest way, but works: 大概记下了最短的方法,但是有效:
$( 'div:eq(0)' ).html(function(){ return '0x40600000<br>'+hex2bytes(0x40600000)}); $( 'div:eq(1)' ).html(function(){ return '0xFF<br>'+hex2bytes(0xFF)}); $( 'div:eq(2)' ).html(function(){ return '0x1<br>'+hex2bytes(0x1)}); $( 'div:eq(3)' ).html(function(){ return '0xF00F0770<br>'+hex2bytes(0xF00F0770)}); function hex2bytes ( hex ) { var binary = "", tmp; hex = hex.toString(16); // Pad while (hex.length % 8) hex = "0" + hex; // Consume 8 or 16 characters long hex string while( hex.length ) { // Work on next 2 hex tmp = hex.slice(0,2); hex = hex.slice(2,Infinity); // convert double hex to 8 binary digits tmp = new Number('0x' + tmp ).toString(2); // Pad while (tmp.length % 8) tmp = "0" + tmp; // Add space and append to previous binary = binary + ' '+ tmp ; } // Remove last [ ] binary = binary.slice(1,Infinity); return binary; }
div { margin-bottom: 1em; font-family: "Courier New", monospace; white-space: pre; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> <div></div> <div></div> <div></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.