main.js (2229B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2021 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' ); 24 var Uint8Array = require( '@stdlib/array/uint8' ); 25 var DataView = require( '@stdlib/array/dataview' ); 26 27 28 // VARIABLES // 29 30 // 2**32 31 var TWO_32 = 4294967296; 32 33 // Initialize a workspace: 34 var WORKSPACE = new Uint8Array( 8 ); 35 36 37 // MAIN // 38 39 /** 40 * Converts a signed 64-bit integer byte array to a double-precision floating-point number. 41 * 42 * ## Notes 43 * 44 * - The function assumes host byte order (endianness). 45 * 46 * @param {Uint8Array} bytes - byte array 47 * @param {integer} stride - stride 48 * @param {NonNegativeInteger} offset - index offset 49 * @returns {number} double-precision floating-point number 50 * 51 * @example 52 * var Uint8Array = require( '@stdlib/array/uint8' ); 53 * 54 * var bytes = new Uint8Array( [ 255, 255, 255, 255, 255, 255, 255, 255 ] ); 55 * var x = fromInt64Bytes( bytes, 1, 0 ); 56 * // returns -1.0 57 */ 58 function fromInt64Bytes( bytes, stride, offset ) { 59 var view; 60 var hi; 61 var lo; 62 var b; 63 var i; 64 65 if ( stride === 1 ) { // contiguous 66 b = bytes; 67 } else { // non-contiguous 68 b = WORKSPACE; 69 for ( i = 0; i < 8; i++ ) { 70 b[ i ] = bytes[ offset ]; 71 offset += stride; 72 } 73 offset = 0; 74 } 75 view = new DataView( b.buffer, b.byteOffset, b.byteLength ); 76 if ( IS_LITTLE_ENDIAN ) { 77 lo = view.getInt32( offset, IS_LITTLE_ENDIAN ); 78 hi = view.getInt32( offset+4, IS_LITTLE_ENDIAN ); 79 } else { 80 hi = view.getInt32( offset, IS_LITTLE_ENDIAN ); 81 lo = view.getInt32( offset+4, IS_LITTLE_ENDIAN ); 82 } 83 if ( lo < 0 ) { 84 lo += TWO_32; 85 } 86 return ( hi*TWO_32 ) + lo; 87 } 88 89 90 // EXPORTS // 91 92 module.exports = fromInt64Bytes;