Go语言十进制转二进制字符串

Go语言十进制转二进制字符串

代码Demo

func Test_2(t *testing.T) {
	// 方法一
	fmt.Println(DecToBin(5))
	// 方法二:导入包"github.com/imroc/biu"
	fmt.Println(biu.ToBinaryString(uint8(5)))
}

// 原理:除2取模是最低位
func DecToBin(n int) string {
	result := ""

	if n == 0 {
		return "0"
	}

	for ;n > 0;n /= 2 {
		lsb := n % 2
		result = strconv.Itoa(lsb) + result
	}

	return result
}

打印

=== RUN   Test_2
101
00000101
--- PASS: Test_2 (0.00s)
PASS

Process finished with exit code 0
posted @ 2020-09-23 13:35  Kingram  阅读(3961)  评论(0编辑  收藏  举报