go implementation of integer binary conversion method

  • 2020-07-21 08:28:54
  • OfStack

int- has been implemented in go > The transformation function of bin, I am just the implementation of the logic of the transformation process, as for the principle I will assume that everyone knows

Only int- is considered in this case > The transformation of the bin

It involves the conversion of positive integers, negative integers, and 0


package main
import (
  "fmt"
  "strconv"
)
//bin Represents the converted number of digits 
func convertToBin(n int,bin int) string{
  var b string
  switch {
  case n==0:
    for i:=0;i<bin;i++{
      b+="0"
    }
  case n>0:
    //strcov.Itoa  will  1  to  "1" , string(1) Directly into assic code 
    for ; n>0;n/=2{
      b=strconv.Itoa(n%2)+b
    }
    // add 0
    j:=bin-len(b)
    for i:=0;i<j;i++{
      b="0"+b
    }
  case n<0:
    n=n*-1
    // fmt.Println(" Become an integer: ",n)
    s:=convertToBin(n,bin)
    // fmt.Println("bin:",s)
    // The not 
    for i:=0;i<len(s);i++{
      if s[i:i+1]=="1"{
        b+="0"
      }else{
        b+="1"
      }
    }
    // fmt.Println("~bin :",b)
    // Convert to plastic, and then add 1  You have to have 64 Otherwise, you may be out of range during the transformation process 
    n,err :=strconv.ParseInt(b,2,64)
    if err!=nil{
      fmt.Println(err)
    }
    // to bin
    //+1
    b=convertToBin(int(n+1),bin)
  }
  return b
}
func main(){
  fmt.Println(
    convertToBin(5,8), //101
    convertToBin(13,8), //1101
    convertToBin(11111,8),
    convertToBin(0,8),
    convertToBin(1,8),
    convertToBin(-5,8),
    convertToBin(-11111,8),
  )
}

Results:

[

5, 131111101-5-11111
00000101 00001101 10101101100111 00000000 00000001 11111011 1010010011001

]

For example, the transformation of -11111:


 Become an integer:  11111
bin: 10101101100111
~bin : 01010010011000
 Results: 1010010011001

For example, the transformation of -1:


 Become an integer:  1
bin: 00000001
~bin : 11111110
 Results: 11111111

conclusion


Related articles: