How to Manipulate Individual Bits in Go: Setting, Clearing, and Checking?

Patricia Arquette
Release: 2024-11-10 14:51:03
Original
960 people have browsed it

How to Manipulate Individual Bits in Go: Setting, Clearing, and Checking?

How to Manipulate Bits in Go

Working with individual bits in an integer is a common task in programming. In Go, there are several ways to achieve this, including the following:

Setting a Bit

To set a particular bit in an integer, you can use the bitwise OR operator (|). For instance:

// Sets the 7th bit in the integer n.
func setBit(n int, pos uint) int {
    return n | (1 << pos)
}
Copy after login

Clearing a Bit

To clear a bit, you can use the bitwise AND operator (&) with a mask. Here's an example:

// Clears the 7th bit in the integer n.
func clearBit(n int, pos uint) int {
    mask := ^(1 << pos)
    return n & mask
}
Copy after login

Checking if a Bit is Set

To check if a particular bit is set, you can use the bitwise AND operator again:

// Returns true if the 7th bit is set in the integer n, false otherwise.
func hasBit(n int, pos uint) bool {
    return (n & (1 << pos)) > 0
}
Copy after login

These functions provide a flexible and efficient way to manipulate individual bits in Go, enabling you to perform bitwise operations with precision.

The above is the detailed content of How to Manipulate Individual Bits in Go: Setting, Clearing, and Checking?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template