search
HomeBackend DevelopmentGolangHow to convert string to integer in golang

How to convert string to integer in golang

Jan 05, 2023 am 11:44 AM
golanggo 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)

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
   }
}

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)

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)

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
    }
}

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
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
In-depth analysis of Go language reflection mechanism and its performance problems in useIn-depth analysis of Go language reflection mechanism and its performance problems in useMay 16, 2025 pm 12:42 PM

The reflection mechanism of Go language is implemented through the reflect package, providing the ability to check and manipulate arbitrary types of values, but it will cause performance problems. 1) The reflection operation is slower than the direct operation and requires additional type checking and conversion. 2) Reflection will limit compiler optimization. 3) Optimization methods include reducing reflection usage, caching reflection results, avoiding type conversions and paying attention to concurrency security.

Learn Go Byte Slice Manipulation: Working with the 'bytes' PackageLearn Go Byte Slice Manipulation: Working with the 'bytes' PackageMay 16, 2025 am 12:14 AM

ThebytespackageinGoisessentialformanipulatingbytesliceseffectively.1)Usebytes.Jointoconcatenateslices.2)Employbytes.Bufferfordynamicdataconstruction.3)UtilizeIndexandContainsforsearching.4)ApplyReplaceandTrimformodifications.5)Usebytes.Splitforeffici

How to use the 'encoding/binary' package to encode and decode binary data in Go (step-by-step)How to use the 'encoding/binary' package to encode and decode binary data in Go (step-by-step)May 16, 2025 am 12:14 AM

Tousethe"encoding/binary"packageinGoforencodinganddecodingbinarydata,followthesesteps:1)Importthepackageandcreateabuffer.2)Usebinary.Writetoencodedataintothebuffer,specifyingtheendianness.3)Usebinary.Readtodecodedatafromthebuffer,againspeci

How do you use the 'encoding/binary' package to encode and decode binary data in Go?How do you use the 'encoding/binary' package to encode and decode binary data in Go?May 16, 2025 am 12:13 AM

The encoding/binary package provides a unified way to process binary data. 1) Use binary.Write and binary.Read functions to encode and decode various data types such as integers and floating point numbers. 2) Custom types can be handled by implementing the binary.ByteOrder interface. 3) Pay attention to endianness selection, data alignment and error handling to ensure the correctness and efficiency of the data.

Go strings package: is it complete for every use case?Go strings package: is it complete for every use case?May 16, 2025 am 12:09 AM

Go's strings package is not suitable for all use cases. It works for most common string operations, but third-party libraries may be required for complex NLP tasks, regular expression matching, and specific format parsing.

What are the limits of the go string package?What are the limits of the go string package?May 16, 2025 am 12:05 AM

The strings package in Go has performance and memory usage limitations when handling large numbers of string operations. 1) Performance issues: For example, strings.Replace and strings.ReplaceAll are less efficient when dealing with large-scale string replacements. 2) Memory usage: Since the string is immutable, new objects will be generated every operation, resulting in an increase in memory consumption. 3) Unicode processing: It is not flexible enough when handling complex Unicode rules, and may require the help of other packages or libraries.

String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool