Why does Go use ^ rather than ~ for unary bitwise-not?
Asked Answered
H

2

6

Most programming languages use ~ to represent a unary bitwise-not operation. Go, by contrast, uses ^:

fmt.Println(^1)  // Prints -2

Why did the Go designers decide to break with convention here?

Hengist answered 25/3, 2016 at 2:15 Comment(0)
E
14

Because ^x is equivalent to m ^ x with m = "all bits set to 1" for unsigned x and m = -1 for signed x. Says so in the spec.

It's similar to how -x is 0 - x

Ermeena answered 25/3, 2016 at 3:5 Comment(0)
E
1

^ operator is similar to + and - operators. For example:

+x == +0x0 + x
+x ==  0x0 + x

-x == -0x0 - x
-x ==  0x0 - x

^x == ^0x0 ^ x
^x ==  0xF ^ x

So ^0 ^ x is equal to ^x.

^0 doesn't change the value of ^x in ^ operation in a similar manner that +0 doesn't change the value of +x in + operation.

Elamitic answered 18/1, 2024 at 7:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.