package main import "fmt" func main() { var num uint = 8 var pos uint = 3 num = num | (1 << pos) fmt.Println(num) }
The original number 8 in binary is 1000. Setting the 3rd bit (0-based) means setting the bit at position 3 to 1. Since it is already 1, the number remains 8. But the code shifts 1 by 3 and ORs it, so it sets bit 3 again, no change. However, the code uses 0-based indexing, so bit 3 is the 4th bit from right. The number 8 is 1000 binary, setting bit 3 again keeps it 8.
Wait, the code sets bit 3 of 8 (1000). 1 << 3 = 8 (1000). OR with 8 is 8. So output is 8.
But option B is 24, which is 11000 binary. That would be setting bit 4 as well.
So correct output is 8.
package main import "fmt" func main() { var num uint = 15 var pos uint = 2 num = num &^ (1 << pos) fmt.Println(num) }
Number 15 in binary is 1111.
Clearing bit 2 (0-based) means clearing the third bit from right.
Bit 2 is 4 in decimal. Clearing it from 15 (1111) results in 1011 binary, which is 11 decimal.
package main import "fmt" func main() { var num uint = 10 var pos uint = 1 num = num ^ (1 << pos) fmt.Println(num) }
Number 10 in binary is 1010.
Toggling bit 1 (second bit from right) flips it.
Bit 1 is 2 in decimal. 10 XOR 2 = 8 (1000 binary).
0-based indexing means the rightmost bit is position 0.
So the 4th bit is the bit at position 4 counting from right starting at 0.
package main import "fmt" func main() { var num uint = 20 var pos int = -1 num = num ^ (1 << pos) fmt.Println(num) }
In Go, shifting by a negative number causes a compile-time error: "negative shift count".
Here, pos is -1, so 1 << pos is invalid.
