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
原文地址:https://www.cnblogs.com/Kingram/p/13717801.html