golang data type conversion

Keywords: Programming

Conversion between string type and int type

Through the function of strconv package, you can easily convert string - > int type and int - > string type

Convert string type to int type

All methods of string type conversion int type are defined in the source file of atio.go

  1. Convert string type to int type
// "111" -> 111
v,err := strconv.Atoi("111")
  1. Convert string type to int64 type
// Parameter 1: string to be converted
// Parameter 2: conversion base, value range (0, 2-36)
// Parameter 3: convert int type, value range (0,8,16,32,64) corresponds to (int,int8,int16,int32,int64)
v,err := strconv.ParseInt("111",10,64)
// If the value of parameter 2 is < 0, 1, or > 36, an invalid base will be prompted
v,err := strconv.ParseInt("111",1,64)
// 0 strconv.ParseInt: parsing "1111": invalid base 1

int to string

All methods to convert int type to string type are defined in the source file itoa.go

  1. Convert int type to string type
// Parameter 1: number of int type to be converted
strconv.Itoa(10)
// 10 -> "10"
  1. Converting int64 type to string type can also be used as a general int conversion string type method
// Parameter 1: number of type int64 to be converted
// Parameter 2: conversion base (2 < = base < = 32)
// 1111 -> "1111"
strconv.FormatInt(1111,10)

// 2 base conversion: 1111 - > 10001010111
// 3 base conversion: 1111 - > 1112011
// 4 Radix conversion: 1111 - > 101113
// 5 base conversion: 1111 - > 13421
// 6 Radix conversion: 1111 - > 5051
// 7 base conversion: 1111 - > 3145
// 8 base conversion: 1111 - > 2127
// 9 base conversion: 1111 - > 1464
// Base conversion: 1111 - > 1111
// 11 base conversion: 1111 - > 920
// 12 base conversion: 1111 - > 787
// 13 Radix conversion: 1111 - > 676
// 14 Radix conversion: 1111 - > 595
// 15 Radix conversion: 1111 - > 4E1
// 16 Radix conversion: 1111 - > 457
// 17 Radix conversion: 1111 - > 3e6
// 18 Radix conversion: 1111 - > 37d
// 19 Radix conversion: 1111 - > 319
// 20 Radix conversion: 1111 - > 2fb
// 21 Radix conversion: 1111 - > 2aj
// 22 Radix conversion: 1111 - > 26b
// 23 Radix conversion: 1111 - > 227
// 24 base conversion: 1111 - > 1m7
// 25 Radix conversion: 1111 - > 1jb
// 26 Radix conversion: 1111 - > 1gj
// 27 Radix conversion: 1111 - > 1E4
// 28 Radix conversion: 1111 - > 1bj
// 29 Radix conversion: 1111 - > 199
// 30 Radix conversion: 1111 - > 171
// 31 Radix conversion: 1111 - > 14q
// 32 Radix conversion: 1111 - > 12n

bool, uint, float types

  1. Convert string to corresponding data type through ParseBool, ParseUint and ParseFloat methods respectively
  2. The corresponding data types are converted to strings through FormatBool, FormatUint and FormatFloat methods respectively

Related parameters refer to the source code (API): bool type conversion class atob.go, unit type conversion class atoi.go, float type conversion class atof.go

Posted by Lirpa on Sun, 03 Nov 2019 13:01:01 -0800