在C#中如何将一个十进制数转换成一个8位的二进制数?,最好能用一条语句实现,

2025-01-04 02:03:38
推荐回答(5个)
回答1:

int i = 10;
string a = Convert.ToString(i, 2);
得到a的值:1010
你要求8位,但是如果的10进制数是12345则转换的值是11000000111001
如果你非要求是8位的话,他转化的值肯定就不正确了。

回答2:

#include
#include
#include
typedef struct node
{
char data;
struct node* next;
}NODE;

int main(void)
{
NODE *q, *head;
int n, d;
NODE *convert(int n, int d);
do{
printf("Enter n,d (2 <= d <= 16):\r\n");
scanf("%d,%d", &n, &d);
}while(d < 2 || d > 16);

head = convert(n, d);

for(q = head; q != NULL; q = q->next)
printf("%c", q->data);
printf("(%d)\n", d);
}

void insert(NODE ** h, char ch)
{
NODE *q;
q = (NODE*)malloc(sizeof(NODE));
q->data = ch;
q->next = *h;
*h = q;
}
NODE *convert(int n, int d)
{
char ch[] = "0123456789ABCDEF";
int m = n<0 ? -n:n;
NODE *q;
q = NULL;
while(m != 0)
{
insert(&q, ch[m%d]);
m/=d;
}
if(n < 0)
insert(&q, '-');
return q;
}

回答3:

这个绝对能用
public string DecimalToBinary(int decimalNum)
{
string binaryNum = Convert.ToString(decimalNum, 2);
int n = binaryNum.Length;
if (binaryNum.Length < 8)
{
for (int i = 0; i < 8 - n; i++)
{
binaryNum = '0' + binaryNum;
}
}
return binaryNum;
}

回答4:

int i = 10;
string a = Convert.ToString(i, 2).PadLeft(8,'0');

回答5:

binaryNum.Length这块有点错误,因为每循环一次,Length都会增加