Operators << and >> in Go: bitwise left and right shifts
Hello everyone! I just started learning Go and came across the `<<` and `>>` operators. The documentation says they are shift operators, but I don't quite understand how they work in practice.\n\nHere's an example code I wrote:\n\n```go\npackage main\n\nimport "fmt"\n\nfunc main() {\n x := 4\n y := x << 2\n z := x >> 1\n fmt.Println(y, z) // Output: 16 2\n}\n```\n\nI expected `x << 2` to give 8 (4 * 2), and `x >> 1` to give 2 (4 / 2). The result 16 and 2 confused me. Why did shifting left by 2 result in multiplication by 4, not by 2? And what do these operators actually mean?\n\nAlso, I've seen the use of `<<` in the context of `1 << iota` when defining constants. Can you explain how that works? I tried to understand bitwise operations, but I get confused with the binary system. I would be grateful for a detailed explanation with
No answers yet.
Log in to leave an answer