Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

How to apply bitwise right shift operator on binary?

How can I perform bitwise right shift on binary?

>> in JS applies to integers. So, 6 >> 1 (bitwise shift right, step 1) shows 3 as result (110 >> 1 = 011 – correct). It is nice, but... Is it possible to work with shift right operator with binary?

I need this: 110 >> 1 working correctly. This will show 55 as result and it is correct. 110 is 01101110. 01101110 >> 1 = 00110111. 00110111 is 55. Correct. But I want 011 as result! How I can do this in js?

Upvotes: 2

Views: 703

Answers (2)

Matt Burland
Matt Burland

Reputation: 45145

Here's one way to do it:

(parseInt("110",2) >> 1).toString(2)      // gives "11"

parseInt can take a radix as a parameter, so if you pass it 2 it will treat the string as binary. So you convert to a number, shift it and then use toString (which conveniently also will take a radix as a parameter) to convert back to a binary string.

Upvotes: 2

Cameron
Cameron

Reputation: 98776

This looks like string manipulation to me. How about:

function shr(x, s) {
    return
        new String('0', Math.min(s, x.length)) +
        x.substr(0, Math.max(0, x.length - s));
}

>>> shr('110', 1)
'011'

Alternatively, you can use the usual bitwise operators and simply convert from a string representation beforehand (once), and convert back to a string representation afterwards (once).

Upvotes: 3

Related Questions