vb.net 如何将十进制数转换为具有固定位的二进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4048443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:06:43  来源:igfitidea点击:

How to convert a decimal number to a binary number with fixed bits

vb.netbinary

提问by m.qayyum

I want to convert numbers from 0 to 15 like this:

我想像这样将数字从 0 转换为 15:

0000
0001
0010
0011
.
.
.
1111

The problem is that when we convert 2 to a binary number it gives only 10 in binary, but I want to convert 2 to 4-bit binary number 0010.

问题是,当我们将 2 转换为二进制数时,它只给出 10 的二进制数,但我想将 2 转换为 4 位二进制数 0010。

回答by Merlyn Morgan-Graham

This code should do what you're looking for:

这段代码应该做你正在寻找的:

For i As Integer = 0 To 15
    Console.WriteLine(Convert.ToString(i, 2).PadLeft(4, "0"C))
Next

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

The "2" in Convert.ToString(i, 2)means binary. PadLeft(4, "0"C)means that if the string isn't four characters, append zeros to the beginning until it is four characters.

中的“2”Convert.ToString(i, 2)表示二进制。 PadLeft(4, "0"C)意味着如果字符串不是四个字符,则在开头附加零直到它是四个字符。