JavaScript 中的字串到二進位制


我們需要編寫一個 JavaScript 函式,該函式僅接受一個字串作為輸入。該函式應構造並返回輸入字串的二進位制表示形式。

例如,

如果輸入字串為:

const str = 'Hello World';

那麼輸出應該為:

const output = '1001000 1100101 1101100 1101100 1101111 100000 1010111
1101111 1110010 1101100 1100100';

例子

程式碼如下:

const str = 'Hello World';
const textToBinary = (str = '') => {
   let res = '';
   res = str.split('').map(char => {
      return char.charCodeAt(0).toString(2);
   }).join(' ');
   return res;
};
console.log(textToBinary('Hello World'));

輸出

控制檯中的輸出為:

1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100

更新日期:2020 年 11 月 23 日

6K+ 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.