Datsik
Datsik

Reputation: 14824

What is the usage of left and right shift bitwise operators >> and <<

I understand the whole, it shifts the bits over

0000 0000 0000 0000 0000 0000 0000 0111 << 1
0000 0000 0000 0000 0000 0000 0000 1110

But why would you want to use these left and right shift operators instead of just typing out the number, where does using these operators actually have a benefit.

I see a lot of answers on Stackoverflow and what the operator accomplishes, but nobody ever says WHY they would use it over just typing out 12345 so like I said, why use them and what is their benefit over just typing the number out you're trying to get?

I came across this code while browsing a package on github:

// ClientVersion is the protocol version that Client implements.
const ClientVersion = 1<<16 | 3<<8 | 0

Which the number comes out to be: 66304

So if this is a constant why not just type const ClientVersion = 66304 why use the operators.

Upvotes: 1

Views: 118

Answers (2)

Salvador Dali
Salvador Dali

Reputation: 222461

If you assume a an integer, then a << x multiplies a by 2^x and a >> x divides b by 2^x, where you use an integer division.

In the case that you described I see no real benefit of using 1<<16 | 3<<8 | 0 instead of 66304 (except of show-off that you can use bitwise operators, which in my stupid opinion is stupid).

But there are ways where I think that they are justifiable (take a look at this question about iota constants).

A couple of other examples (not only related to Go):

  • check if n-th bit is set x & (1<<n)
  • set the n-th bit x | (1<<n)
  • many other manipulations with n-th bit.

Upvotes: 1

T McKeown
T McKeown

Reputation: 12847

When you require small memory footprints, being able to use a single byte to hold 256 different options instead of using a big string array or more bytes then you will use these.

Embedded systems make use of bit wise operations to turn on/off options, any system that needs to be somewhat self sustainable and not depend on a rich external datastore would benefit from this technique.

Upvotes: 0

Related Questions