簡體   English   中英

Javascript將字符串轉換為具有固定長度的二進制文件

[英]Javascript convert string to binary with a fixed length

是否有一種優雅的方法將一些字符串轉換為二進制並獲得具有固定長度的結果?
內置函數是: parseInt(str, 10).toString(2) ,但它正在縮短長度。

例如,如果我想長度= 8位,那么myFunction("25")將返回00011001而不是11001

我知道我可以在開頭添加零,但這對我來說似乎不是一種優雅的方式。

似乎最優雅的方法是編寫(或獲取某個地方)缺失的抽象並組合它們以獲得所需的結果。

 // 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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM