main.js (1803B)
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 25 26 // VARIABLES // 27 28 var NBITS = 8; 29 30 31 // MAIN // 32 33 /** 34 * Creates an unsigned 8-bit integer from a literal bit representation. 35 * 36 * @param {BinaryString} bstr - string which is a literal bit representation 37 * @throws {Error} must provide a string with a length equal to `8` 38 * @returns {uinteger8} unsigned 8-bit integer 39 * 40 * @example 41 * var bstr = '01010101'; 42 * var val = fromBinaryStringUint8( bstr ); 43 * // returns 85 44 * 45 * @example 46 * var bstr = '00000000'; 47 * var val = fromBinaryStringUint8( bstr ); 48 * // returns 0 49 * 50 * @example 51 * var bstr = '00000010'; 52 * var val = fromBinaryStringUint8( bstr ); 53 * // returns 2 54 * 55 * @example 56 * var bstr = '11111111'; 57 * var val = fromBinaryStringUint8( bstr ); 58 * // returns 255 59 */ 60 function fromBinaryStringUint8( bstr ) { 61 var sum; 62 var i; 63 if ( bstr.length !== NBITS ) { 64 throw new Error( 'invalid argument. Input string must have a length equal to '+NBITS+'. Value: `'+bstr+'`.' ); 65 } 66 sum = 0; 67 for ( i = 0; i < bstr.length; i++ ) { 68 if ( bstr[ i ] === '1' ) { 69 sum += pow( 2, (NBITS-i-1) ); 70 } 71 } 72 return sum; 73 } 74 75 76 // EXPORTS // 77 78 module.exports = fromBinaryStringUint8;