Skip to content

Binary Parser

binaryParser.ts

ts
const intToBinary = (num: number): string => Number(num).toString(2);
const parseBinToInteger = (bin: string): number => parseInt(bin, 2);

const strToBinary = (str: string): string =>
  [...str]
    .map(char => {
      const bin = char.charCodeAt(0).toString(2);
      return `${bin}`.padStart(8, "0");
    })
    .join(" ");

const parseBinToString = (binary: string): string =>
  binary
    .split(" ")
    .map(bin => {
      const charCode = parseInt(bin, 2);
      return String.fromCharCode(charCode);
    })
    .join("");

binaryParser.spec.ts

ts
describe("Integer", () => {
  it("Should returns binary", () => {
    expect(intToBinary(42)).toEqual("101010");
  });

  it("Should returns integer", () => {
    expect(parseBinToInteger("00101010")).toEqual(42);
  });
});

describe("String", () => {
  it("Should returns binary", () => {
    expect(strToBinary("Hello")).toEqual("01001000 01100101 01101100 01101100 01101111");
  });

  it("Should returns string", () => {
    expect(parseBinToString("01010111 01101111 01110010 01101100 01100100")).toEqual("World");
  });
});

Released under the MIT License.