Home > Backend Development > Golang > How to Convert Numeric Values to Binary Strings in Go?

How to Convert Numeric Values to Binary Strings in Go?

Mary-Kate Olsen
Release: 2024-11-26 17:34:10
Original
569 people have browsed it

How to Convert Numeric Values to Binary Strings in Go?

Converting Numeric Values to Binary Strings in Go

Developers working with numerical data may encounter the need to represent numbers as binary strings. Go offers the strconv (string conversion) package for this purpose, providing the FormatInt function.

Problem:

Convert a numeric value (e.g., 123) to its binary representation (e.g., "1111011").

Solution:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    n := int64(123)

    binary := strconv.FormatInt(n, 2)
    fmt.Println(binary) // 1111011
}
Copy after login

Explanation:

  • The strconv.FormatInt function takes two arguments:

    • i: The numeric value to be converted.
    • base: The target base (2 for binary representation).
  • The function returns a string representing the number in the specified base. By setting the base to 2, we obtain the binary representation.
  • In the example provided, the integer 123 is converted to its binary form, resulting in the string "1111011".

Demo:

You can try out the demo here: http://play.golang.org/p/leGVAELMhv

The above is the detailed content of How to Convert Numeric Values to Binary Strings in Go?. 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