add spaces between bits group
This commit is contained in:
parent
3b2348f977
commit
b23eb4d7c0
|
|
@ -210,11 +210,11 @@ describe("Bitmap", () => {
|
||||||
bitmap.set(i);
|
bitmap.set(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
const resultString = "0101010101010101";
|
const resultString = "01010101 01010101";
|
||||||
|
|
||||||
expect(bitmap.toString()).toEqual(resultString);
|
expect(bitmap.toString()).toEqual(resultString);
|
||||||
expect(String(bitmap)).toEqual(resultString);
|
expect(String(bitmap)).toEqual(resultString);
|
||||||
expect(`bitmap debug: ${bitmap}`).toEqual("bitmap debug: 0101010101010101")
|
expect(`bitmap debug: ${bitmap}`).toEqual(`bitmap debug: ${resultString}`)
|
||||||
|
|
||||||
const bitmap2 = Bitmap.fromString(bitmap.toString());
|
const bitmap2 = Bitmap.fromString(bitmap.toString());
|
||||||
expect(bitmap2.toString()).toEqual(bitmap.toString());
|
expect(bitmap2.toString()).toEqual(bitmap.toString());
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,9 @@ export class Bitmap {
|
||||||
* @returns {string} Binary string representing the full contents of the bitmap.
|
* @returns {string} Binary string representing the full contents of the bitmap.
|
||||||
*/
|
*/
|
||||||
public toString(): string {
|
public toString(): string {
|
||||||
return Array.from(this.bits).map((x) => x.toString(2).padStart(8, '0')).join('')
|
return Array.from(this.bits)
|
||||||
|
.map(x => x.toString(2).padStart(8, '0'))
|
||||||
|
.join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -86,14 +88,17 @@ export class Bitmap {
|
||||||
* @throws {Error} If the input length is not divisible by 8.
|
* @throws {Error} If the input length is not divisible by 8.
|
||||||
*/
|
*/
|
||||||
static fromString(s: string): Bitmap {
|
static fromString(s: string): Bitmap {
|
||||||
if (s.length % 8 !== 0) {
|
// allow "00000001 00000010", "0000000100000010", etc.
|
||||||
|
const cleaned = s.replace(/\s+/g, '');
|
||||||
|
|
||||||
|
if (cleaned.length % 8 !== 0) {
|
||||||
throw new Error("Bitmap string must be aligned to bytes (len % 8 == 0)");
|
throw new Error("Bitmap string must be aligned to bytes (len % 8 == 0)");
|
||||||
}
|
}
|
||||||
|
|
||||||
const bytes = new Uint8Array(s.length / 8);
|
const bytes = new Uint8Array(cleaned.length / 8);
|
||||||
|
|
||||||
for (let i = 0; i < bytes.length; i++) {
|
for (let i = 0; i < bytes.length; i++) {
|
||||||
const byteStr = s.slice(i * 8, i * 8 + 8);
|
const byteStr = cleaned.slice(i * 8, i * 8 + 8);
|
||||||
bytes[i] = parseInt(byteStr, 2);
|
bytes[i] = parseInt(byteStr, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue