c语言进制转换

 结果打印到控制台

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<Windows.h>


void to2(int num)
{
	if (num == 0)
	{
		return;
	}
	else {
		to2(num / 2);
		printf("%d", num % 2);
	}
}

void to8(int num)
{
	if (num == 0)
	{
		return;
	}
	else {
		to8(num / 8);
		printf("%d", num % 8);
	}
}

void to16(int num)
{
	if (num == 0)
	{
		return;
	}
	else {
		to16(num / 16);
		printf("%x", num % 16);
	}
}

void main()
{
	int num = 0;
	scanf("%d", &num);
	to2(num);
	printf("\n");
	to8(num);
	printf("\n");
	to16(num);
	printf("\n");

	system("pause");

}


或者  结果保存到字符串

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<Windows.h>


void to2str(int num, int i,char str2[32])
{
	if (num == 0)
	{
		return;
	}
	else {
		to2str(num / 2, i + 1, str2);
		str2[i] = (num % 2) + '0';
			
	}
}

void to8str(int num, int i, char str8[38])
{
	if (num == 0)
	{
		return;
	}
	else {
		to8str(num / 8, i + 1, str8);
		str8[i] = (num % 8) + '0';

	}
}

void to16str(int num, int i, char str16[316])
{
	if (num == 0)
	{
		return;
	}
	else {
		to16str(num / 16, i + 1, str16);	

		if (num % 16 < 10) {
			str16[i] = (num % 16) + '0';
		}
		else {
			str16[i] = (num % 16)-10 + 'A';
		}

	}
}


void main() {

	int num = 0;
	scanf("%d", &num);
	char str2[32] = { 0 };
	char str16[32] = { 0 };
	char str8[32] = { 0 };
	to2str(num, 0, str2);
	_strrev(str2);
	printf("\n%s", str2);

	to16str(num, 0, str16);
	_strrev(str16);
	printf("\n%s", str16);

	to8str(num, 0, str8);
	_strrev(str8);
	printf("\n%s", str8);

	system("pause");

	system("pause");
}

转载地址:https://edu.51cto.com/center/course/lesson/index?id=628372

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值