Comparing version 1.0.11 to 1.0.12
@@ -8,2 +8,3 @@ /** | ||
const HEX_FORMAT = /^(0x)?([0-9a-fA-F]+)$/; | ||
const BIT_FORMAT = /^(0b|0B)?([01]+)$/; | ||
const HEX_MAP = "0123456789abcdef"; | ||
@@ -22,12 +23,28 @@ const HEX_MAP_R = { | ||
Object.defineProperty(ArrayBuffer.prototype, 'toString', { | ||
value:function(padding=false){ | ||
value:function(format=16, padding=false){ | ||
const bytes = new Uint8Array(this); | ||
let hex = ''; | ||
for(let i=0; i<bytes.length; i++) { | ||
const value = bytes[i]; | ||
hex += HEX_MAP[(value&0xF0)>>>4] + HEX_MAP[value&0x0F]; | ||
let result = ''; | ||
switch(format) { | ||
case 16: | ||
for(let i=0; i<bytes.length; i++) { | ||
const value = bytes[i]; | ||
result += HEX_MAP[(value&0xF0)>>>4] + HEX_MAP[value&0x0F]; | ||
} | ||
break; | ||
case 2: | ||
for(let i=0; i<bytes.length; i++) { | ||
const value = bytes[i]; | ||
for (let k=7; k>=0; k--) { | ||
result += ((value >>> k) & 0x01) ? '1' : '0'; | ||
} | ||
} | ||
break; | ||
default: | ||
throw new RangeError( "Unsupported numeric representation!" ); | ||
} | ||
return padding ? hex : hex.replace(/^0+/, ''); | ||
return padding ? result : result.replace(/^0+/, ''); | ||
}, | ||
@@ -165,2 +182,28 @@ configurable:true, enumerable:false, writable:true | ||
} | ||
else | ||
if ( conversion_info === "bits" ) { | ||
const matches = input.match(BIT_FORMAT); | ||
if ( !matches ) { | ||
throw new RangeError( "Input argument is not a valid bit string!" ); | ||
} | ||
let [,,bit_string] = matches; | ||
if ( bit_string.length % 8 !== 0 ) { | ||
bit_string = '0'.repeat(bit_string.length%8) + bit_string; | ||
} | ||
const buff = new Uint8Array((bit_string.length/8)|0); | ||
for ( let i=0; i<buff.length; i++ ) { | ||
const offset = i * 8; | ||
let value = (bit_string[offset]==='1'?1:0); | ||
for (let k=1; k<8; k++) { | ||
value = (value << 1) | (bit_string[offset + k]==='1'?1:0); | ||
} | ||
buff[i] = value; | ||
} | ||
return buff.buffer; | ||
} | ||
else { | ||
@@ -167,0 +210,0 @@ return UTF8Encode(input).buffer; |
{ | ||
"name": "extes", | ||
"version": "1.0.11", | ||
"version": "1.0.12", | ||
"description": "A tiny library that extends native js with some handy tools", | ||
@@ -5,0 +5,0 @@ "main": "index.mjs", |
17859
577