main.js (2003B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 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 pow = require( '@stdlib/math/base/special/pow' ); 24 var toUint32 = require( './../../../../float64/base/to-uint32' ); 25 26 27 // VARIABLES // 28 29 var NBITS = 32; 30 31 32 // MAIN // 33 34 /** 35 * Creates an unsigned 32-bit integer from a literal bit representation. 36 * 37 * @param {BinaryString} bstr - string which is a literal bit representation 38 * @throws {Error} must provide a string with a length equal to `32` 39 * @returns {uinteger32} unsigned 32-bit integer 40 * 41 * @example 42 * var bstr = '01010101010101010101010101010101'; 43 * var val = fromBinaryStringUint32( bstr ); 44 * // returns 1431655765 45 * 46 * @example 47 * var bstr = '00000000000000000000000000000000'; 48 * var val = fromBinaryStringUint32( bstr ); 49 * // returns 0 50 * 51 * @example 52 * var bstr = '00000000000000000000000000000010'; 53 * var val = fromBinaryStringUint32( bstr ); 54 * // returns 2 55 * 56 * @example 57 * var bstr = '11111111111111111111111111111111'; 58 * var val = fromBinaryStringUint32( bstr ); 59 * // returns 4294967295 60 */ 61 function fromBinaryStringUint32( bstr ) { 62 var sum; 63 var i; 64 if ( bstr.length !== NBITS ) { 65 throw new Error( 'invalid argument. Input string must have a length equal to '+NBITS+'. Value: `'+bstr+'`.' ); 66 } 67 sum = 0; 68 for ( i = 0; i < bstr.length; i++ ) { 69 if ( bstr[ i ] === '1' ) { 70 sum += pow( 2, (NBITS-i-1) ); 71 } 72 } 73 return toUint32( sum ); 74 } 75 76 77 // EXPORTS // 78 79 module.exports = fromBinaryStringUint32;