s-binary
v0.0.13
Published
Simple operations for binary strings
Downloads
18
Maintainers
Readme
s-binary
Work in progress
Usage example
var binary = require('s-binary');
binary.toInt('11001100'); // returns 204
// 8bit 5 - 9
var five = binary.toBinary(5, 8); // '00000101'
var nine = binary.toBinary(9, 8); // '00001001'
var negativeNine = binary.complement(nine); // '11110111'
var sum = binary.add(five, negativeNine); // '11111100'
var checkAnswer = binary.complement(sum); // '00000100'
binary.toInt(checkAnswer); // 4
Installation
npm install --save s-binary
Available methods
This module assumes big-endian byte order
Unit conversion
binary to integer
binary.toInt('11001100'); // returns 204
binary to hex
binary.toHex('11001100'); // returns 'cc'
binary to Unicode
binary.toUnicode('0110100001101001'); // returns 'hi'
string/integer/buffer to binary
binary.toBinary(204); // returns '11001100'
binary.toBinary('foo'); // returns '011001100110111101101111'
Arithmetic
Simple addition
binary.add('111', '1'); // returns '1000'
Bit addition
binary.addBits('1', '1'); // returns ['0', '1']
// ------------------------------- sum ^ -- ^ carry
Multiplication
binary.multiply('1010', '10'); // returns '10100'
// 10 ^ 2 ^ 20 ^
Division
binary.divide('1010', '101'); // returns '10'
// 10 ^ 5 ^ 2 ^
Logic
NOT
binary.not('1011'); // returns '0100'
AND
binary.and('101', '110'); // returns '100'
OR
binary.or('101', '110'); // returns '111'
XOR
binary.xor('101', '110'); // returns '011'
NAND
binary.nand('101', '110'); // returns '011'
NOR
binary.nor('101', '110'); // returns '000'
Two's complement
binary.complement('00000101'); // returns '11111011'
Helper methods
(Left) pad
binary.pad('01', 4); // returns '0001' (left pad)
Equalize lengths by padding shorter value
binary.equalize('11', '0001'); // returns ['0011', '0001']
Split
binary.split('1111111100000000', 8); // returns ['11111111', '00000000']
LSB (get least significant bits)
Last bit from each byte. Note: bytes can be of any length.
var data = ['01000100', '11001100', '01010101'];
binary.lsb(data); // returns '001'