2020年8月1日 星期六

[ 文章收集 ] Convert between int, int64 and string

Source From Here
int/int64 to string
Use strconv.Itoa to convert an int to a decimal string.
  1. s := strconv.Itoa(97// s == "97"  
Warning: In a plain conversion the value is interpreted as a Unicode code point, and the resulting string will contain the character represented by that code point, encoded in UTF-8:
  1. s := string(97// s == "a"  
Use strconv.FormatInt to format an int64 in a given base:
  1. var n int64 = 97  
  2. s := strconv.FormatInt(n, 10// s == "97" (decimal)  
  3. s = strconv.FormatInt(n, 16// s == "61" (hexadecimal)  
string to int/int64
Use strconv.Atoi to parse a decimal string to an int:
  1. s := "97"  
  2. if n, err := strconv.Atoi(s); err == nil {  
  3.     fmt.Println(n+1)  
  4. else {  
  5.     fmt.Println(s, "is not an integer.")  
  6. }  
  7. // Output: 98  
Use strconv.ParseInt to parse a decimal string (base 10) and check if it fits into an int64.
  1. s := "97"  
  2. n, err := strconv.ParseInt(s, 1064)  
  3. if err == nil {  
  4.     fmt.Printf("%d of type %T", n, n)  
  5. }  
  6. // Output: 97 of type int64  
The two numeric arguments represent a base (0, 2 to 36) and a bit size (0 to 64). If the first argument is 0, the base is implied by the string’s prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise; The second argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.

int to int64 (and back)
The size of an int is implementation-specific, it’s either 32 or 64 bits, and hence you won’t lose any information when converting from int to int64.
  1. var n int = 97  
  2. m := int64(n) // safe  
However, when converting to a shorter integer type, the value is truncated to fit in the result type's size.
  1. var m int64 = 2 << 32  
  2. n := int(m)    // truncated on machines with 32-bit ints  
  3. fmt.Println(n) // either 0 or 4,294,967,296  
* See Maximum value of an int for code to compute the size of an int.
* See Pick the right one: int vs. int64 for best practices.

General formatting (width, indent, sign)
The fmt.Sprintf function is a useful general tool for converting data to string:
  1. s := fmt.Sprintf("%+8d"97)  
  2. // s == "     +97" (width 8, right justify, always show sign)  
Supplement
OpenHome Go - 起步走 - 型態、變數、常數、運算子: 變數宣告、常數宣告
Golang - 如何在 string 與其他 type 互轉,e.g. int, bool, float

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...