简体   繁体   English

将二进制字符串分成两半

[英]Spliting the binary string in half

I am trying to split binary number in half and then just add 4 zeroes. 我正在尝试将二进制数分成两半,然后仅添加4个零。

For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. 例如,对于10111101我想只以数字的前半部分结尾,其余数字为零。 What I want to end up would be 10110000 . 我要结束的是10110000

Can you help me with this? 你能帮我吗?

Use substring to split and then looping to pad 使用子字符串进行拆分,然后循环至填充

var str = '10111101';

var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
    output += "0";
}

alert(output)

try this (one-liner) 试试这个(单线)

var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);

sample output 样本输出

['10111101','10110000']

我想您正在使用JavaScript ...

"10111101".substr(0, 4) + "0000";

It's a bit unclear if you are trying to operate on numbers or strings. 还不清楚您是否要对数字或字符串进行运算。 The answers already given do a good job of showing how to operate on a strings. 已经给出的答案很好地说明了如何对字符串进行操作。 If you want to operate with numbers only, you can do something like: 如果只想使用数字进行运算,则可以执行以下操作:

// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
    var count;
    for (count = 0; count < 32; count ++) {
        if (word & (1 << (31 - count))) {
            break;
        }
    }
    return count;
}

function zeroBottomHalf (num) {
    var digits    = 32 - nlz32(num);       // count # of digits in num
    var half      = Math.floor(digits / 2);// how many to set to 0
    var lowerMask = (1 << half) - 1;       //mask for lower bits: 0b00001111
    var upperMask = ~lowerMask             //mask for upper bits: 0b11110000
    return num & upperMask;
}

var before = 0b10111101;
var after  = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after  = ', after.toString(2));  // outputs: 10110000

In practice, it is probably simplest to covert your number to a string with num.toString(2) , then operate on it like a string as in one of the other answers. 实际上,用num.toString(2)将您的数字隐藏为字符串,然后像其他答案之一一样像字符串一样操作它,可能是最简单的。 At the end you can convert back to a number with parseInt(str, 2) 最后,您可以使用parseInt(str, 2)转换回数字

If you have a real number, not string, then just use binary arithmetic. 如果您有一个实数而不是字符串,那么只需使用二进制算术即可。 Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply: 假设您的电话号码始终为8个二进制数字-您的问题对此有点含糊-只需简单地:

console.log((0b10111101 & 0b11110000).toString(2))
// 10110000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM