golang和python的二进制转换

1.二进制转换规则

比如13,对13整除2,余数1,整除变为6,依次类推

13/2=6余1

6/2=3余0

3/2=1余1

1/2=0余1

所以最后的结果为1101

2.python

def converToBin(n):
    result = ""
    while n>0:
        lsb=n%2
        n = n // 2
        result=str(lsb)+result
    return result

print(converToBin(5))
print(converToBin(13))
print(converToBin(2344))

#101
#1101
#100100101000

3.golang

package main

import (
    "fmt"
    "strconv"
)

func converToBin(n int )string{
    result:=""
    for ; n>0;n/=2{
        lsb:=n%2
        //strconv.Itoa(lsb)int转str
        result=strconv.Itoa(lsb)+result
    }
    return result
}

func main() {
    fmt.Println(
        converToBin(5),
        converToBin(13),
        converToBin(2344),)
}

#101 1101 100100101000

 

posted @ 2019-06-01 22:12  Maple_feng  阅读(487)  评论(0编辑  收藏  举报