Search code examples
javascriptbinaryappendconverters

Javascript convert string to binary with a fixed length


Is there an elegant way to convert some string to binary and get a result with a fixed length?
The built-in function is: parseInt(str, 10).toString(2), but it's cutting the length.

For example, if I want length = 8 bits, then myFunction("25") will return 00011001 instead of just 11001.

I know that I can append zeros to the beginning, but it doesn't seems like an elegant way to me.


Solution

  • Seems like the most elegant way to do that is to write (or get somewhere) missing abstractions and compose them to achieve desired result.

    // lodash has this function
    function padStart(string, length, char) {
      //  can be done via loop too:
      //    while (length-- > 0) {
      //      string = char + string;
      //    }
      //  return string;
      return length > 0 ?
        padStart(char + string, --length, char) :
        string;
    }
    
    function numToString(num, radix, length = num.length) {
      const numString = num.toString(radix);
      return numString.length === length ?
        numString :
        padStart(numString, length - numString.length, "0")
    }
    
    console.log(numToString(parseInt("25", 10), 2, 8));