How to convert string to integer in golang

青灯夜游
Release: 2023-01-05 11:44:22
Original
5376 people have browsed it

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!