function doubleToByteArray(number) { var buffer = new ArrayBuffer(8); // JS numbers are 8 bytes long, or 64 bits var longNum = new Float64Array(buffer); // so equivalent to Float64 longNum[0] = number; return Array.from(new Int8Array(buffer)).reverse(); // reverse to get little endian}function interactiveExample() { var input = parseFloat(document.getElementById('input').value); var output = document.getElementById('output'); var result = doubleToByteArray(input); output.innerHTML = '[' + result[0]; for (var i = 1; i < result.length; i++) { output.innerHTML += ', ' + result[i]; } output.innerHTML += ']';}document.getElementById('input').value = Math.PI;interactiveExample(); <input type="number" id="input" step="0.01" onchange="interactiveExample()" /><div id="output"></div>I am trying to convert some Java code into JavaScript which is needed for the application I am working on. I am stuck on one class and its methods that convert a variable of type double to long, and then long to a byte array that consists of 8 bytes representing that long number. The Java code is as follows: public static byte[] doubleToByteArray(double number) { // double to long representation long longNum = Double.doubleToLongBits(number); // long to 8 bytes return new byte[] {(byte)((longNum >>> 56) & 0xFF), (byte)((longNum >>> 48) & 0xFF), (byte)((longNum >>> 40) & 0xFF), (byte)((longNum >>> 32) & 0xFF), (byte)((longNum >>> 24) & 0xFF), (byte)((longNum >>> 16) & 0xFF), (byte)((longNum >>> 8) & 0xFF), (byte)((longNum >>> 0) & 0xFF)}; } // end doubleToByte(.)How would I go about doing this in JavaScript? My first issue is with the doubleToLongBits method. Does anything similar exist in JavaScript? Furthermore, how to cast a variable into a Byte?Thank you in advance. 解决方案 Based on Brian's answer and on your desired representation, you can use the typed array as follows:function doubleToByteArray(number) { var buffer = new ArrayBuffer(8); // JS numbers are 8 bytes long, or 64 bits var longNum = new Float64Array(buffer); // so equivalent to Float64 longNum[0] = number; return Array.from(new Int8Array(buffer)).reverse(); // reverse to get little endian}function interactiveExample() { var input = parseFloat(document.getElementById('input').value); var output = document.getElementById('output'); var result = doubleToByteArray(input); output.innerHTML = '[' + result[0]; for (var i = 1; i < result.length; i++) { output.innerHTML += ', ' + result[i]; } output.innerHTML += ']';}document.getElementById('input').value = Math.PI;interactiveExample();<input type="number" id="input" step="0.01" onchange="interactiveExample()" /><div id="output"></div> 这篇关于JavaScript中的双字节数组转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-30 06:41