将位转换为二进制值

时间:2021-03-29 01:13:08

标签: javascript

function calculateBinary(bits) {
var bitValue = 0;

for(var i=0; i<bits.length; i++) {
  if(bits[0] === '1') {
    bitValue += 128;
  } else if (bits[1] === '1') {
    bitValue += 64;
  } else if (bits[2] === '1') {
    bitValue += 32;
  } else if (bits[3] === '1') {
    bitValue += 16;
  } else if (bits[4] === '1') {
    bitValue += 8;
  } else if (bits[5] === '1') {
    bitValue += 4;
  } else if (bits[6] === '1') {
    bitValue += 2;
  } else if (bits[7] === '1') {
    bitValue += 1;
  } 
}
  return bitValue;
}

calculateBinary('11111111');

// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)

为什么我的 for 循环将位字符串的每次迭代都视为位 [0]?返回值是 '1028' 或 12 * 8。我做错了什么导致我的 For 循环?

1 个答案:

答案 0 :(得分:1)

考虑

for(var i=0; i<bits.length; i++) {
  if(bits[0] === '1') {
    bitValue += 128;
  } else if 

您没有检查循环内的索引 - 您总是检查 bits[0]然后如果该条件不成功,您将进入 {{1 }} 等,不考虑索引。

去除循环。

bits[1]

或者使用循环内的索引来计算要添加的数量。

function calculateBinary(bits) {
  var bitValue = 0;
  if (bits[0] === '1') {
    bitValue += 128;
  }
  if (bits[1] === '1') {
    bitValue += 64;
  }
  if (bits[2] === '1') {
    bitValue += 32;
  }
  if (bits[3] === '1') {
    bitValue += 16;
  }
  if (bits[4] === '1') {
    bitValue += 8;
  }
  if (bits[5] === '1') {
    bitValue += 4;
  }
  if (bits[6] === '1') {
    bitValue += 2;
  }
  if (bits[7] === '1') {
    bitValue += 1;
  }
  return bitValue;
}

console.log(calculateBinary('11111111'));

// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)

(或者,甚至更好,don't reinvent the wheel