Javascript convert string to binary with fixed length
Is there an elegant way to convert some string to binary and get a fixed length result?
Built-in function:, parseInt(str, 10).toString(2)
but it shortens the length.
For example, if I want length = 8 bits, it myFunction("25")
will 00011001
just return instead 11001
.
I know that I can add leading zeros, but that doesn't seem like an elegant way to me.
+3
source to share
1 answer
It seems like the most elegant way to do this is to write (or get somewhere) no abstractions and compose them to achieve the 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));
+1
source to share