Could someone please explain to me the usage of <<
and >>
in Go? I guess it is similar to some other languages.
相关问题
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- how to install private repo using glide golang
- How to convert a string to a byte array which is c
- IntelliJ 2017.1.2 GOLANG debug does not work on br
相关文章
- Can I run a single test in a suite?
- How to check if a request was cancelled
- Is it possible to implement an interface with unex
- Construction an logical expression which will coun
- How to access value of first index of array in Go
- Embedded Interface
- How to represent an array with mixed types
- go tutorial select statement
From the spec at http://golang.org/doc/go_spec.html, it seems that at least with integers, it's a binary shift. for example, binary 0b00001000 >> 1 would be 0b00000100, and 0b00001000 << 1 would be 0b00010000.
Go apparently doesn't accept the 0b notation for binary integers. I was just using it for the example. In decimal, 8 >> 1 is 4, and 8 << 1 is 16. Shifting left by one is the same as multiplication by 2, and shifting right by one is the same as dividing by two, discarding any remainder.
The super (possibly over) simplified definition is just that
<<
is used for "times 2" and>>
is for "divided by 2" - and the number after it is how many times.So
n << x
is "n times 2, x times". Andy >> z
is "y divided by 2, z times".For example,
1 << 5
is "1 times 2, 5 times" or 32. And32 >> 5
is "32 divided by 2, 5 times" or 1.All the other answers give the more technical definition, but nobody laid it out really bluntly and I thought you might want that.
In decimal math, when we multiply or divide by 10, we effect the zeros on the end of the number.
In binary, 2 has the same effect. So we are adding a zero to the end, or removing the last digit
Go's << and >> are similar to shifts (that is: division or multiplication by a power of 2) in other languages, but because Go is a safer language than C/C++ it does some extra work when the shift count is a number.
Shift instructions in x86 CPUs consider only 5 bits (6 bits on 64-bit x86 CPUs) of the shift count. In languages like C/C++, the shift operator translates into a single CPU instruction.
The following Go code
prints
while a C/C++ program would print
The << and >> operators are Go Arithmetic Operators.
They are basically Arithmetic operators and its the same in other languages here is a basic PHP , C , Go Example
GO
GO Demo
C
C Demo
PHP
PHP Demo
They would all output