add spaces between bits group

This commit is contained in:
Eugene 2025-12-06 12:30:06 +03:00
parent 3b2348f977
commit b23eb4d7c0
2 changed files with 11 additions and 6 deletions

View File

@ -210,11 +210,11 @@ describe("Bitmap", () => {
bitmap.set(i);
}
const resultString = "0101010101010101";
const resultString = "01010101 01010101";
expect(bitmap.toString()).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());
expect(bitmap2.toString()).toEqual(bitmap.toString());

View File

@ -73,7 +73,9 @@ export class Bitmap {
* @returns {string} Binary string representing the full contents of the bitmap.
*/
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.
*/
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)");
}
const bytes = new Uint8Array(s.length / 8);
const bytes = new Uint8Array(cleaned.length / 8);
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);
}