Example 1: Using the Golang XOR Operator for Integer
We use the XOR operator for integer values to perform the bitwise exclusive OR (XOR) operations. Each bit in a new value that results from the XOR method on the appropriate bits of the operands when two operands are used is the outcome of the XOR operation.
import "fmt"
func main() {
x := 15
y := 25
z := x ^ y
fmt.Printf("Value of z is %d\n", z)
}
In the beginning, we establish the primary package that is utilized to develop the standalone executable programs. The Go “fmt” package, which contains functions for formatted I/O, is then imported using the “import” modifier. In this code, it is used to print the output to the console. We then declare the main() function where the “x” and “y” variables are declared and initialized with the values of 15 and 25, respectively.
The “:=” syntax here is used for short variable declaration in Go, where the value that is assigned to the variable deduces its type. Next, we create another variable which is “z” where we calculated the bitwise XOR (exclusive OR) of “x” and “y”. The “^” operator in Go indicates the XOR operator. Finally, we call the print statement to print the value of “z” that is inserted into the formatted string. The “%d” is a format specifier that represents an integer.
The value after performing the XOR operation is obtained in the following output:
Example 2: Using the Golang XOR Operator for an Integer from the Terminal
We can also use the Golang XOR operator for an integer input from the terminal. Here, we can see the modified program:
import "fmt"
func main() {
var n1 int=0
var n2 int=0
var result int=0
fmt.Printf("Enter the first number: ")
fmt.Scanf("%d",&n1)
fmt.Printf("Enter the second number: ")
fmt.Scanf("%d",&n2)
result = n1 ^ n2
fmt.Printf("Result: %d",result)
}
We define the necessary package for this program first. Then, we defined the main() function for the program implementation. There, we declare three integer variables – “n1”, “n2”, and the “result” – and initialize all of them with the value of “0”. The user is then prompted to enter the first number using the fmt.Printf() function after that.
In this case, the “n1” variable is filled with an integer number that is read from the user through the fmt.Scanf() function. Similar to the first number, the second number is also requested from the user, and its result is saved in the “n2” variable. The “^” operator is used to perform the bitwise XOR operation on “n1” and “n2”, and the result is assigned to the “result” variable.
As we provided the inputs in the following console, the program displays the result of the XOR operation on the console:
Example 3: Using the Golang Logical XOR Operator for Boolean
We discussed the bitwise XOR operator in the prior examples. Here, we use a logical XOR operator between two Boolean values.
import (
"fmt"
)
func main() {
A := true
B := false
fmt.println((A || B) && !(A && B))
}
The Boolean variables “A” and “B” should first be given the entries of “true” and “false”, respectively. Then, we use the logical OR (||), logical AND (&&), and logical NOT (!) operators to perform a Boolean expression: (A || B) && !(A && B). The expression evaluates to “true” if either A or B is true but not both. Otherwise, it evaluates to “false”.
The output of the XOR operator is retrieved as the Boolean value:
Example 4: Using the Golang XOR Operator for the Encryption of String
Additionally, we can use the XOR operator for simple encryption and decryption of strings in Go based on the provided key. Here’s the demonstration of the code where the XOR operator is used to encrypt and decrypt the string.
import (
"fmt"
)
func xorEncryptDecrypt(MyData string, key byte) string {
encrypted := make([]byte, len(MyData))
for i := 0; i < len(MyData); i++ {
encrypted[i] = MyData[i] ^ key
}
return string(encrypted)
}
func main() {
MyData := "Welcome Golang Tutorials"
key := byte(30)
encryptedVal := xorEncryptDecrypt(MyData, key)
fmt.Println("Encrypted value:", encryptedVal)
decryptedVal := xorEncryptDecrypt(encryptedVal, key)
fmt.Println("Decrypted Value:", decryptedVal)
}
We establish the xorEncryptDecrypt() function that takes the “MyData” parameters of type string and “key” of type byte. The function creates an “encrypted” byte slice with the same length as “MyData” to store the encrypted result. We then employ the “for” loop which iterates over each character in “MyData.” Within the loop, it performs the XOR operation (^) between the byte value of the current character in “MyData” and the key byte.
The associated index of the encrypted slice contains the outcome. After encrypting all the characters, the encrypted slice is converted back to a string using string(encrypted) and return it. Next, we have the main() function where we define a “MyData” string and a “key” key byte. The xorEncryptDecrypt() function is called with “MyData” and “key” to encrypt the string, and the encrypted result is stored in the “encryptedVal” variable. The xorEncryptDecrypt() function is called again with the “encryptedVal” and “key” to decrypt the encrypted string. The decrypted result is stored in the “decryptedVal” variable.
The output displays the encrypted and decrypted values of the “MyData” string using the XOR encryption algorithm with the specified key:
Example 5: Using the Golang XOR Operator on Hexa Byte Values
Moreover, the XOR operator can also be used to manipulate and combine the hexadecimal byte values at the bit level. The following example shows the usage of Go’s XOR operator on hexadecimal byte data:
import "fmt"
func main() {
var hexaByte byte = 0x0F
fmt.Printf("%08b\n", hexaByte)
fmt.Printf("%08b\n", ^hexaByte)
}
We define the “hexaByte” as the hexadecimal byte value of “0x0F” and the “xorVal” as the hexadecimal byte value of “0x2C”. We then perform the bitwise XOR operation between “hexaByte” and “xorVal” using the “^” operator and store the result in the “res” variable. Finally, we print the binary representation of the result using the “%08b” format specifier in the fmt.Printf() function. The “08” part ensures that the output is formatted as 8 characters with leading zeros if necessary.
The output displays the result of the bitwise XOR operation which corresponds to the following binary representation:
Conclusion
We can manipulate the bits, encrypt the data, detect errors, and more in Go by leveraging the XOR operator. We provided various examples of using the XOR operator in Go that are easy to comprehend. The XOR operator in Go is a potent tool to swiftly complete the bitwise operations and manage a variety of programming problems.