如何根据二进制输入判断各索引位比特状态并映射对应项状态
如何根据二进制字符串生成对应状态项数组?
我需要检查数值的每个索引位置比特是否置位,举个例子:给定二进制输入binaryInput为"1100",要生成result数组。映射规则如下:
item1 on -> 0
item1 off -> 1
item2 on -> 0
item2 off -> 1
item3 on -> 0
item3 off -> 1
item4 on -> 0
item4 off -> 1
规则是找出二进制输入中所有值为1的位,将对应的状态项加入result数组。注意要从右往左读取二进制字符串,比如输入"1100"时,结果应为["item3 off", "item4 off"]。
我尝试了以下代码,但没能得到正确结果,求指导正确实现方式:
const data = { "item1 on" : "0", "item1 off" : "1", "item2 on" : "0", "item2 off" : "1", "item3 on" : "0", "item3 off" : "1", "item4 on" : "0", "item4 off" : "1", } function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value); } for (var i = 0; i < input.length; i++) { var status= getKeyByValue(data, input[i]); if (input[i] === "1") { result.push(status); } }
问题分析
你的代码存在两个核心问题:
- 二进制字符串读取方向错误:你从左往右遍历字符串,但需求要求从右往左读取比特位。比如输入"1100",左到右的索引0对应最左侧的"1",实际应对应item4,而非item1。
getKeyByValue函数存在歧义:当传入值"1"时,函数会返回第一个匹配的键(即"item1 off"),无法对应到正确的item编号。
解决方案
方式一:重构数据结构,明确映射关系
直接定义每个item的状态与比特位的对应关系,遍历方向改为从右往左:
// 定义每个item的状态对应规则 const itemMap = [ { name: 'item1', offBit: '1', onBit: '0' }, { name: 'item2', offBit: '1', onBit: '0' }, { name: 'item3', offBit: '1', onBit: '0' }, { name: 'item4', offBit: '1', onBit: '0' }, ]; function getResult(binaryInput) { const result = []; // 从右往左遍历二进制字符串 for (let i = binaryInput.length - 1; i >= 0; i--) { const currentBit = binaryInput[i]; // 计算当前比特位对应的item索引(最右侧对应item1,即数组索引0) const itemIndex = binaryInput.length - 1 - i; if (currentBit === '1') { result.push(`${itemMap[itemIndex].name} off`); } } return result; } // 测试示例 const input = "1100"; console.log(getResult(input)); // 输出: ["item3 off", "item4 off"]
方式二:基于原有代码修改,修正遍历方向与映射逻辑
保留原有数据结构,修改getKeyByValue函数增加item编号匹配,同时调整遍历顺序:
const data = { "item1 on": "0", "item1 off": "1", "item2 on": "0", "item2 off": "1", "item3 on": "0", "item3 off": "1", "item4 on": "0", "item4 off": "1", }; // 增加itemNumber参数,精准匹配对应item的状态键 function getKeyByValue(object, value, itemNumber) { return Object.keys(object).find(key => key.includes(`item${itemNumber}`) && object[key] === value ); } function getResult(input) { const result = []; // 从右往左遍历字符串 for (let i = input.length - 1; i >= 0; i--) { const currentBit = input[i]; // 计算当前比特位对应的item编号 const itemNumber = input.length - i; if (currentBit === "1") { const status = getKeyByValue(data, currentBit, itemNumber); result.push(status); } } return result; } // 测试示例 const input = "1100"; console.log(getResult(input)); // 输出: ["item3 off", "item4 off"]
内容的提问来源于stack exchange,提问作者Sarahrb
相关产品推荐
相关产品推荐

