Home Backend Development Golang How to convert string to integer in golang

How to convert string to integer in golang

Jan 05, 2023 am 11:44 AM
golang go language

Conversion method: 1. Use Atoi() to convert the integer of the string type into the int type, the syntax is "strconv.Atoi(str)"; 2. Use ParseInt() to convert the string It is an integer value, and the sign is accepted, and the syntax is "strconv.ParseInt(str,10,64)"; 3. Use ParseUnit() to convert the string into an integer value, and the sign is not accepted, and the syntax is "strconv.ParseUint (str,10,64)".

How to convert string to integer in golang

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

The strconv package in Go language implements mutual conversion between basic data types and their string representations.

The strconv package implements the conversion of basic data types and their string representations. It mainly includes the following common functions: Atoi(), Itia(), parse series, format series, and append series.

The following introduces several functions for converting strings to integers.

Atoi()

Atoi() function is used to convert an integer of string type to int type, The function signature is as follows.

func Atoi(s string) (i int, err error)
Copy after login

If the incoming string parameter cannot be converted to int type, an error will be returned.

package main

import "fmt"
import "strconv"

func main() {
   s1 := "100"
      i, err := strconv.Atoi(s1)
   if err != nil {
      fmt.Println("can't convert to int")
   } else {
      fmt.Printf("type:%T value:%#v\n", i, i) //type:int value:100
   }
}
Copy after login

How to convert string to integer in golang

Parse series functions

Parse class functions are used to convert strings into given types. Values: ParseBool(), ParseFloat(), ParseInt(), ParseUint(). Among them, ParseInt() and ParseUnit() are used to convert strings to integers.

ParseInt()

ParseInt() is a function that converts a string into a number

func ParseInt(s string, base int, bitSize int) (i int64, err error)
Copy after login

Returns the integer value represented by the string, accepts positive negative.

  • base specifies the base (2 to 36). If base is 0, it will be judged from the prefix of the string. "0x" is hexadecimal and "0" is octal. System, otherwise it is decimal;

  • bitSize specifies the integer type that the result must be assigned without overflow, 0, 8, 16, 32, and 64 respectively represent int, int8, int16, and int32 , int64;

  • The err returned is of type *NumErr. If the syntax is incorrect, err.Error = ErrSyntax; if the result exceeds the type range err.Error = ErrRange.

ParseUnit()

func ParseUint(s string, base int, bitSize int) (n uint64, err error)
Copy after login

ParseUint is similar to ParseInt but does not accept signs and is used for unsigned integers.

Example:

package main

import "fmt"
import "strconv"

func main() {
	i, err1 := strconv.ParseInt("-2", 10, 64)
	u, err2 := strconv.ParseUint("2", 10, 64)
	if err1 != nil {
      fmt.Println("can't convert to int")
    } else {
      fmt.Printf("type:%T value:%#v\n", i, i) //type:int64 value:2
    }
	if err2 != nil {
      fmt.Println("can't convert to int")
    } else {
      fmt.Printf("type:%T value:%#v\n", u, u) //type:uint64 value:0x2
    }
}
Copy after login

How to convert string to integer in golang

Both the ParseInt() and ParseUnit() functions have two return values, the first return value is the converted value, and the second return value is the error message of failed conversion.

Extended knowledge: Integer types in go

Go language provides both signed and unsigned integer types, including int8, int16, int32 and int64 are four signed integer types with completely different sizes, corresponding to signed integers of 8, 16, 32 and 64 bit (binary bit) sizes respectively. Corresponding to this are uint8, uint16, uint32 and uint64. Unsigned integer type.

In addition, there are two integer types, int and uint, which respectively correspond to the word length (machine word size) of a specific CPU platform. Int represents a signed integer, which is the most widely used, and uint represents an unsigned integer. In actual development, due to differences in compilers and computer hardware, the integer size that int and uint can represent will vary between 32bit or 64bit.

In most cases, we only need int, an integer type, which can be used for loop counters (variables that control the number of loops in for loops), indexes of arrays and slices, and any general purpose Integer operators, usually the int type is also the fastest in processing speed.

The rune type used to represent Unicode characters is equivalent to the int32 type, and is usually used to represent a Unicode code point. The two names can be used interchangeably. Similarly, byte and uint8 are also equivalent types. The byte type is generally used to emphasize that the value is a primitive data rather than a small integer.

Finally, there is an unsigned integer type uintptr, which does not specify a specific bit size but is large enough to accommodate pointers. The uintptr type is only needed in low-level programming, especially where Go language interacts with C language function libraries or operating system interfaces.

Although the sizes of int, uint and uintptr may be equal in some specific operating environments, they are still different types, such as int and int32. Although the size of the int type may also be 32 bits, When you need to use the int type as an int32 type, you must explicitly convert the type, and vice versa.

Signed integers in the Go language are represented in 2's complement form, that is, the highest bit is used to represent the sign bit. The value range of an n-bit signed number is from -2(n- 1) to 2(n-1)-1. All bits of an unsigned integer are used to represent non-negative numbers, and the value range is 0 to 2n-1. For example, an int8 type integer ranges from -128 to 127, while a uint8 type integer ranges from 0 to 255.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to convert string to integer in golang. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

See all articles