如何将十进制数转换为具有固定位的二进制数 [英] How to convert a decimal number to a binary number with fixed bits

查看:115
本文介绍了如何将十进制数转换为具有固定位的二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

0000
0001
0010
0011
.
.
.
1111

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

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.

推荐答案

此代码应满足您的需求:

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

Convert.ToString(i, 2)中的"2"表示二进制. PadLeft(4, "0"C)表示如果字符串不是四个字符,则在开头添加零,直到四个字符为止.

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.

这篇关于如何将十进制数转换为具有固定位的二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆