十进制转换成二进制c语言

时间:2025-03-07 22:59:28 网络游戏

在C语言中,将十进制数转换为二进制数可以通过多种方法实现。以下是几种常见的方法:

方法一:使用位运算符

```c

include

include

char *itoa(int n, char *ps) {

int i;

const static int size = (CHAR_BIT * sizeof(int));

for (i = size - 1; i >= 0; i--, n >>= 1) {

ps[i] = (n & 1) + '0'; // 在数组中以ASCII存储

}

ps[size] = '\0';

return ps;

}

int main() {

int num = 10;

char binary;

itoa(num, binary);

printf("Decimal %d to binary: %s\n", num, binary);

return 0;

}

```

方法二:递归方法

```c

include

void to_binary(unsigned int n) {

int r;

r = n % 2;

if (n >= 2)

to_binary(n / 2);

putchar(r == 0 ? '0' : '1');

}

int main() {

unsigned int num = 10;

to_binary(num);

printf("\n");

return 0;

}

```

方法三:循环方法

```c

include

include

void decimalToBinary(int n, char *binaryStr) {

int index = 0;

while (n > 0) {

int remainder = n % 2;

binaryStr[index++] = remainder + '0';

n = n / 2;

}

binaryStr[index] = '\0';

}

int main() {

int number = 156;

char binary;

decimalToBinary(number, binary);

printf("Decimal %d to binary: %s\n", number, binary);

return 0;

}

```

方法四:除二取余法

```c

include

long tobinary(int dno) {

long bno = 0, rem, f = 1;

while (dno != 0) {

rem = dno % 2;

bno = bno + rem * f;

f = f * 10;

dno = dno / 2;

}

return bno;

}

int main() {

int dno;

printf("Enter any decimal number: ");

scanf("%d", &dno);

long bno = tobinary(dno);

printf("The Binary value is: %ld\n", bno);

return 0;

}

```

方法五:字符串处理法

```c

include

include

int bintodeci(char *s) {

int res = 0, sign = 1, i;

char *p;

i = 1;

if (*s == '-') { // 如果输入的是负数,则数据符号是-

sign = -1;

s++;

}

p = s;

while (*p != '\0') p++; // p一直指向字符串最后的反斜杠0,只为了从右往左运算

while (p != s) {

int remainder = *p - '0';

res = res * 10 + remainder;

p--;

}

return res * sign;

}

int main() {

char s;

printf("请输入二进制形式的数\n");

gets(s);

printf("转换成十进制形式是:%d\n", bintodeci(s));

return 0;

}

```

这些方法各有优缺点,可以根据具体需求和场景选择合适的方法进行十进制到二进制的转换。