bits.Add() Function in Golang with Examples

Go language provides inbuilt support for bits to implement bit counting and manipulation functions for the predeclared unsigned integer types with the help of bits package. This package provides Add() function which is used to find the sum with the carry of a, b and carry, i.e, sum = a + b + carry. Here the value of carry must be 0 or 1, otherwise, the behavior is undefined. To access Add() function you need to add a math/bits package in your program with the help of the import keyword.

Syntax:

func Add(a, b, carry uint) (sum, carryout unit)

Parameters: This function takes three parameters of uint type, i.e., a, b, and carry. The value of carry parameter is either 1 or 0.

Return Value: This function return two values of uint type, i.e., sum and carryout. Here sum contains the result of a + b + carry and carryout is either 1 or 0.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate bits.Add() Function
package main
  
import (
    "fmt"
    "math/bits"
)
  
// Main function
func main() {
  
    // Finding sum and carry 
    // of the specified numbers
    // Using Add() function
    nvalue_1, carry := bits.Add(2, 3, 0)
    fmt.Println("Sum:", nvalue_1)
    fmt.Println("Carry:", carry)
  
}

chevron_right


Output:

Sum: 5
Carry: 0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate bits.Add() Function
package main
  
import (
    "fmt"
    "math/bits"
)
  
// Main function
func main() {
  
    // Finding sum and carry 
    // of the specified numbers
    // Using Add() function
    var a, b, carry uint = 4, 5, 1
    sum, carryout := bits.Add(a, b, carry)
    fmt.Println("Number 1:", a)
    fmt.Println("Number 2:", b)
    fmt.Println("Carry:", carry)
    fmt.Println("Sum:", sum)
    fmt.Println("Carry:", carryout)
  
}

chevron_right


Output:

Number 1: 4
Number 2: 5
Carry: 1
Sum: 10
Carry: 0



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.