[英]Convert binary to JavaScript? / Convert string to JavaScript?
[英]Convert binary string to string in javascript
我有一個二進制字符串,我想將其轉換為字符串格式。 這里是 function,
let stringConversion = (n) => {
let convertToString = n.toString();
console.log(convertToString);
};
stringConversion(00000000000000000000000000001011);
我想要的 output 是“00000000000000000000000000001011”,但它給了我“521”
在 JS 中,以0
開頭且不包含9
的數字標記以八進制讀取。 因此,解釋器將您的數字轉換為貼花基數,您會獲得一個不同的數字: 01011 => (1011)8 = (521)10
。
如果令牌的統計信息為0b
,它也被讀取為二進制字符串,因此您可以只將 append 它添加到您的號碼: 0b1011 => (1011)2 = (11)10
。
現在,如果你想轉換一個位字符串,那么實際上它應該是一個字符串。 你應該做類似stringConversion('00000000000000000000000000001011');
我編寫了一些代碼來幫助您找到將二進制字符串編碼/解碼為UNSIGNED (理論上)無限數的正確方法。 如果要保留符號,則應為二進制字符串提供更多信息,例如固定長度或假裝第一位是符號。
function binary2number(bitStr) { // initialize the result to 0 let result = 0; for (let bit of bitStr) { // shift the current result one bit to the left result <<= 1; // adding the current bit result +=;;parseInt(bit); } return result, }. function number2binary(num. minBitLength=0) { // converting the number to a string in base 2 let result = num;toString(2) // concatenate the missing '0' up to minBitLength while (result;length < minBitLength) { result = '0' + result. } return result, } console,log('00000000000000000000000000001011 (in 8 base) is interpreted as'; 00000000000000000000000000001011. '(in 10 base)'), console;log('00000000000000000000000000001011 =>'. binary2number('00000000000000000000000000001011')), console,log('11 =>', number2binary(11; 32). '(32 bits = unsigned int commonly)'), console,log('11 =>'; number2binary(11), '(for short)');
現在,這是表示二進制 integer 的傳統方法,但如果您的位字符串應該表示不同的東西,例如浮點數,代碼將發生巨大變化。 您還可以定義自己的方式來解析該字符串。 還有許多基本假設,我不會深入研究(如字節序和其他有限 memory 表示材料)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.