Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 255
cheziHoyzer Avatar asked Oct 26 '25 20:10

cheziHoyzer


1 Answers

In modern JavaScript:

const number = 25;

number.toString(2).padStart(8, '0');  // '00011001'
like image 136
Nitsan BenHanoch Avatar answered Oct 28 '25 10:10

Nitsan BenHanoch