11

I am seeing ^0 in the code base.

Example:

type stat struct {
  ...
  min int64
  ...
}

newStat := stat{min: ^0}

What does ^0 mean?

underscore_d
  • 6,309
  • 3
  • 38
  • 64
samol
  • 18,950
  • 32
  • 88
  • 127

1 Answers1

27

According to the docs:

^x bitwise complement is m ^ x with m = "all bits set to 1" for

unsigned x and m = -1 for signed x

So ^x inverts each of the bits in x, eg. 0101 becomes 1010. This means that ^0 is the same as ~0 in other mainstream languages.

When using two's complement to represent negative numbers (which most programming languages do), the value of the bitwise complement of zero (where all bits are 1) is -1. So this is a way to write:

newStat := stat{min: -1}
doubledup
  • 18
  • 4
Murilo Vasconcelos
  • 4,677
  • 24
  • 27
  • Hey thanks for the response. I am a Go beginner and I still have no idea what this means. What is ~0? What is bitwise complement? Could you please clarify? Thanks in advance!! – samol Oct 03 '13 at 22:23
  • 4
    The bitwise complement is take each bit from an data type and invert it. For example 0 in 4-bit binary is 0000 its bitwise complement is 1111. The same way that 10 in a 4-bit binary is 1010 and its complement is 0101. – Murilo Vasconcelos Oct 03 '13 at 22:28
  • 1
    For further reference, read on [bitwise operations](http://en.wikipedia.org/wiki/Bitwise_operation) in general. – justinas Oct 04 '13 at 11:56
  • Thanks very much. This might sound stupid but what is the point of a bitwise operation? why didn't they just write stat{min: -1} but instead had to go through this trouble to write ^0 ? – samol Oct 04 '13 at 19:47
  • I don't know where did you get that piece of code, but my guess is: because they want to. That is not a very advanced thing to do, and shows a feature of the language. There are cases where doing bitwise operations are faster than simple arithmetic. You can google for example `xor eax, eax`. But that is definitely not the case in your example. – Murilo Vasconcelos Oct 04 '13 at 20:01
  • 4
    My guess: They're not using 'min' the way you'd normally think of an integer (to count things), they're using it as a set of bits. If the last bit is 1 it means something, if the second to last bit is 1, it means some other thing, etc. In Go, code of this style might use '1 << iota' for constants. Anyway '^0' arguably conveys "an integer with all bits set to 1" better than '-1' does. – Tyler Oct 05 '13 at 21:09
  • By the way, it seems unlikely that '^0' is any faster (or slower) than '-1': I suspect the compiler just writes both of them as a literal 0xFFFFFFFF. – Tyler Oct 05 '13 at 21:10
  • @MatrixFrog yes all constants are hard coded into the binary. – wingerse Jun 17 '17 at 18:47
  • Does this mean that Go requires two's complement, or that it would add code to ensure the CPU returns -1 if it implements signed ints differently? – underscore_d Apr 13 '18 at 18:46