javascript進位轉換

來源:互聯網
上載者:User

標籤:英文   依次   number   拼接   題目   .com   href   get   present   

一、文法說明1、parseInt()

parseInt:將字串轉換成整數

parseInt(string, radix)

  • string要被解析的字串。
  • 可選。表示要解析的數位基數。該值介於 2 ~ 36 之間。

    如果省略該參數或其值為 0,則數字將以 10 為基礎來解析。
    如果它以 “0x” 或 “0X” 開頭,將以 16 為基數。

    如果該參數小於 2 或者大於 36,則 parseInt() 將返回 NaN。

2、toString()

toString()方法屬於Object對象,JavaScript的許多內建對象都重寫了該函數,以實現更適合自身的功能需要。

類型 行為描述
Array 將 Array 的每個元素轉換為字串,並將它們依次串連起來,兩個元素之間用英文逗號作為分隔字元進行拼接。
Boolean 如果布爾值是true,則返回"true"。否則返回"false"。
Date 返回日期的文本表示。
Error 返回一個包含相關錯誤資訊的字串。
Function 返回如下格式的字串,其中 functionname 是一個函數的名稱,此函數的 toString 方法被調用: "function functionname() { [native code] }"
Number 返回數值的字串表示。還可返回以指定進位表示的字串,請參考Number.toString()。
String 返回 String 對象的值。
Object(預設) 返回"[object ObjectName]",其中 ObjectName 是物件類型的名稱。
2、進位轉換
//十進位轉其他進位    var x=110;  alert(x);  alert(x.toString(2));  alert(x.toString(8));  alert(x.toString(32));  alert(x.toString(16));  //其他轉十進位  var x=‘110‘;  alert(parseInt(x,2));  //6    =>以2進位解析110alert(parseInt(x,8));  //72    =>以8進位解析110alert(parseInt(x,16)); //272    =>以16進位解析110//其他轉其他  //先用parseInt轉成十進位再用toString轉到目標進位  alert(String.fromCharCode(parseInt(141,8)))  alert(parseInt(‘ff‘,16).toString(2));   

 

三、測試題目

Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

 

<script>    function countBits(n) {        var resultString = n.toString(2);        var l = resultString.length;        var resultNum = 0;        for (var i = 0; i < l; i++) {            resultNum += resultString[i]-0;        }        console.log(resultNum);        return resultNum;    }    func(1234);    </script>

 

本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載註明出處:http://www.cnblogs.com/starof/p/6693318.html有問題歡迎與我討論,共同進步。

javascript進位轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.