How do I manipulate binary numbers in GO?

How can I handle and do mathematical operations in GO, such as adding or dividing two binary numbers?

In Python, there is something like this:

bin(int('101101111', 2) + int('111111', 2))

Which works fine unless you need to use floating point numbers.

If you know them at “development time” use 0b prefixed nuimeric constants as in this example:

https://play.golang.org/p/X9iVtsZruuF

There is also the strconv pacakge, which provides functionality to parse strings in any base you like.

1 Like

Thanks a lot, building on your answer, I came up with the below understanding:

Use 0b to define a binary number and use #b to print it, as in below:

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, playground")

	x := 0b101101111
	y := 0b111111
	fmt.Printf("\nx + y = %#b that is %v + %v = %v ", x+y, x, y, x+y)

	a := 0b1000000001
	b := 0b111111111
	fmt.Printf("\na - b = %#b that is %v - %v = %v ", a-b, a, b, a-b)

	c := 0b1000000001
	d := 0b111111111
	fmt.Printf("\nc * d = %#b that is %v * %v = %v ", c*d, c, d, c*d)

	h := 0b10110101101
	r := 0b101
	fmt.Printf("\nh / r = %#b that is %v / %v = %v ", h/r, h, r, h/r)
	fmt.Printf("\nh %% r = %#b that is %v %% %v = %v ", h%r, h, r, h%r)
}

Note the double % in the last line, we use %% to escape %

Output is:

x + y = 0b110101110 that is 367 + 63 = 430 
a - b = 0b10 that is 513 - 511 = 2 
c * d = 0b111111111111111111 that is 513 * 511 = 262143 
h / r = 0b100100010 that is 1453 / 5 = 290 
h % r = 0b11 that is 1453 % 5 = 3 

Same is applicable for Hexa and Octal numbers, use 0o to define an octal number and use #o to print it, and use 0x to define a hexa number and use #x to print it, below an example:

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, playground")

	x := 1234

	fmt.Printf("\nNumber %v =>\n In the binary system is: %#b \n In the hexgonal system is: %#x \n In the octal system is: %#o ", x, x, x, x)

	O := 0o2322
	fmt.Printf("\n%#o is %v ", O, O)

	H := 0x4d2
	fmt.Printf("\n%#x is %v ", H, H)

	B := 0b10011010010
	fmt.Printf("\n%#b is %v ", B, B)
}

And the output is:

Hello, playground

Number 1234 =>
 In the binary system is: 0b10011010010 
 In the hexgonal system is: 0x4d2 
 In the octal system is: 02322 
02322 is 1234 
0x4d2 is 1234 
0b10011010010 is 1234 

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.